Python面向对象编程 类的定义
-
类中的变量是类的数据属性,函数为类的方法(函数)属性
-
类定义的所有变量和函数都会被存在dict的字典中(命名空间)
-
类在定义之后代码就可以被执行,不需要被调用
定义类:
class People: # python3默认继承object类 == class People(object): country = 'China' def walk(self): print("%s is walking!" % self)
属性访问
print(People.country) # People.__dict__['country'] # China
新增/修改属性
People.country = 'Chinese' People.name = '中国' print(People.country,People.name) # Chinese 中国
删除属性
People.name = '中国' print(People.name) del People.name print(People.__dict__.get('name')) # 中国 # None
class People: # python3默认继承object类 == class People(object): country = 'China' def __init__(self, name, sex, age): self.Name = name self.Sex = sex self.Age = age # {'Name': 'Conan', 'Sex': 'male', 'Age': 8}
-
__init__ 方法为对象定制自己特有的特征,在对象实例化时python自动调用
实例化过程
-
创建一个空对象obj
-
触发__init__ 方法对obj进行初始化,People.init(conan,'Conan','male',8)

浙公网安备 33010602011771号