python基础-面向对象(三)类和实例属性的增删改查
1.直接点属性,就可查看,修改,增加。
删除用del
class Chinese: country = 'China' def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def cook_food(self): print('%s正在做饭' % self.name) person1 = Chinese('alex', 11, '男') # 查看 print('修改前>', Chinese.country) # 修改前> China # 类修改数据属性 Chinese.country = 'CHINA' print('>>>来自类', Chinese.country) # >>>来自类 CHINA print('>>来自对象', person1.country) # >>来自对象 CHINA 对象只有数据属性,类修改了函数属性,对象调用也是修改后的 # 类修改函数属性。一般不在类外部用。 def test(): print('from test') Chinese.cook_food = test print(Chinese.cook_food()) # from test None # 对象修改数据属性,只是在__dict__中加了键值对 person1.country = 'Japan' print(person1.__dict__) # {'name': 'alex', 'age': 11, 'gender': '男', 'country': 'Japan'} print(Chinese.country) # CHINA # 删除del del Chinese.country del person1.age print(Chinese.__dict__) # {'__module__': '__main__', '__init__': <function Chinese.__init__ at 0x0000000002164EE8>, 'cook_food': <function test at 0x0000000002164F78>, '__dict__': <attribute '__dict__' of 'Chinese' objects>, '__weakref__': <attribute '__weakref__' of 'Chinese' objects>, '__doc__': None} print(person1.__dict__) # {'name': 'alex', 'gender': '男', 'country': 'Japan'}
总结:类修改属性后,对象在调用的都是修改后的属性。
对象修改属性,只是在自己的__dict__增加键值对,对类属性无影响。(append是个例外)
append——追加。在原基础上追加
2.属性和变量的区别:属性的调用要么用__dict__[],要么用点,没有点的调用是调用的变量
country='Japan' class Chinese: country = 'China' def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender print(country) #这个country没有点,所以是变量,不是数据属性 def cook_food(self): print('%s正在做饭' % self.name) p1=Chinese('alex',11,'男')


浙公网安备 33010602011771号