对象与实例属性补充

class Chinese:
    country='China'
    def __init__(self,name):
        self.name=name

    def play_ball(self,ball):
        print('%s 正在打 %s' %(self.name,ball))
p1=Chinese('alex')
print(p1.country)                   #China
p1.country='日本'                   #只是在实例的字典属性里增加了一对country:日本

print('类的--->',Chinese.country)     #类的---> China
print('实例的',p1.country)             #实例的 日本

 

country='中国'
class Chinese:
    def __init__(self,name):
        self.name=name

    def play_ball(self,ball):
        print('%s 正在打 %s' %(self.name,ball))
p1=Chinese('alex')          #一实例化就会触发__init__函数
print(p1.country)      #只能找到类那一层
#报错:AttributeError: 'Chinese' object has no attribute 'country'

 

country='中国-----------'
class Chinese:
    country='中国'
    def __init__(self,name):
        self.name=name
        print('--->',country)

    def play_ball(self,ball):
        print('%s 正在打 %s' %(self.name,ball))

print(Chinese.__dict__)
print(Chinese.country)          #中国
p1=Chinese('alex')              #---> 中国-----------
print('实例--------》',p1.country)         #实例--------》 中国


#用加    .   的方式去找属性,只能找到类那一层,且不是类属性就是实力属性
#其他的方式,就跟类和实例没关系,不会在类或实例的字典属性里找,直接在类的外层找

 

# class Chinese:
#     country='China'
#     def __init__(self,name):
#         self.name=name
#
#     def play_ball(self,ball):
#         print('%s 正在打 %s' %(self.name,ball))
# p1=Chinese('alex')
#
# print(p1.country)           #China
# p1.country='Japan'
# print(Chinese.country)      #China

class Chinese:
    country='China'
    l=['a','b']
    def __init__(self,name):
        self.name=name

    def play_ball(self,ball):
        print('%s 正在打 %s' %(self.name,ball))
p1=Chinese('alex')
print(p1.l)                 # ['a', 'b']
# p1.l=[1,2,3]              #就是新增了实例的属性
# print(Chinese.l)            #['a', 'b']
# print(p1.__dict__)          #{'name': 'alex', 'l': [1, 2, 3]}
p1.l.append('c')                #拿到的是类的属性
print(p1.__dict__)            #{'name': 'alex'}
print(Chinese.l)                #['a', 'b', 'c']

 

posted @ 2019-03-21 11:57  wind_y  阅读(236)  评论(0编辑  收藏  举报