python 面向对象整理 --------1.类和实例的属性

1.类的属性

# /usr/bin/env
# coding = utf-8
class Chinese:
  #类的属性在这 country
= 'China' def __init__(self, name):
     #实例的属性在这 self.name
= name def play_ball(self, ball): print('%s正在打%s' % (self.name, ball)) #查看属性 print(Chinese.country) #修改属性 Chinese.country='Japan' print(Chinese.country) p1=Chinese('alex') print(p1.__dict__) print(p1.country) #增加属性 Chinese.dang='' print(Chinese.dang) print(p1.dang) #删除属性 del Chinese.dang del Chinese.country print(Chinese.__dict__) # print(Chinese.country)

结果:

China
Japan
{'name': 'alex'}
Japan
党
党
{'__module__': '__main__', '__init__': <function Chinese.__init__ at 0x0000028B584A66A8>, 'play_ball': <function Chinese.play_ball at 0x0000028B584A6620>, 
'__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None}

增加函数属性:

#定义一个函数
def eat_food(self,food):
    print('%s正在吃%s'%(self.name,food))

#把这个函数给类
Chinese.eat=eat_food

print(Chinese.__dict__)
p1.eat('')

#test
def test(self):
    print('test')

Chinese.play_ball=test
p1.play_ball()

结果:

alex正在吃屎
test

 

2.实例的属性:

 

#/usr/bin/env
#coding = utf-8
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.__dict__)


#增加
p1.age=18
print(p1.__dict__)
print(p1.age)

#不要修改底层的属性字典
# p1.__dict__['sex']='male'
# print(p1.__dict__)
# print(p1.sex)

#修改
p1.age=19
print(p1.__dict__)
print(p1.age)

 

结果:

{'name': 'alex'}
{'name': 'alex', 'age': 18}
18
{'name': 'alex', 'age': 19}
19

 

posted on 2018-07-24 22:45  solarzc  阅读(72)  评论(0)    收藏  举报