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自动调用

实例化过程
  1. 创建一个空对象obj

  2. 触发__init__ 方法对obj进行初始化,People.init(conan,'Conan','male',8)

 

posted @ 2018-01-21 21:07  若言-从心开始  阅读(145)  评论(0)    收藏  举报