一.实例变量与类变量
- 实例变量,属于对象,每个对象中各自维护自己的数据。
类变量,属于类,可以被所有对象共享,一般用于给对象提供公共数据(类似于全局变量)。 ```python class Person(object): country = “中国”
def init(self, name, age):
self.name = nameself.age = age
def show(self):
# message = "{}-{}-{}".format(Person.country, self.name, self.age)message = "{}-{}-{}".format(self.country, self.name, self.age)print(message)
print(Person.country) # 中国
p1 = Person(“武沛齐”,20) print(p1.name) print(p1.age) print(p1.country) # 中国
p1.show() # 中国-武沛齐-20
**类变量可以通过类访问,也可以通过对象访问****如果通过对象,对类变量进行修改——无法真正修改,而是在实例变量中添加****类变量继承遵循成员继续顺序**<a name="sccwu"></a>###<a name="nYM4C"></a>### 二.在方法内部本身的变量,即不是实例变量也不是类变量而是函数中的临时变量<a name="z6mUr"></a>### 三.变量的访问与修改<a name="H6gJV"></a>#### 1.私有变量外部修改:如果知道了在内部的变量名,是可以通过对象或者类对其进行修改的```pythonclass F(object):def __init__(self, name):self.name = nameobj1 = F('侯震宇')obj1.name = '张佳奇'print(obj1.name) # 张佳奇del obj1.nameprint(obj1.name) # 报错,没有这个attribute
2.类变量的外部查看(外部无法修改)
class F(object):Country = '中国'def __init__(self, name):self.name = nameprint(F.Country) # 通过类进行查看obj1 = F('侯震宇')print(obj1.Country) # 通过对象进行查看
2.修改是通过cls.变量名完成,实例变量的访问修改是通过self.变量名完成
class People(object):People_can_do = {'行走', '说话', '会使用文字', '会使用工具', '吃饭'}def __init__(self, name, age):self.name = nameself.age = agedef func1(self):print('你的名字是{},你的年龄是{}'.format(self.name, self.age))@classmethoddef ask_do(cls,do_sth):if do_sth not in cls.People_can_do:while True:choice = input('暂时没有这个功能,是否需要添加Y/N:').upper()if choice not in {'Y','N'}:print('选择不合法,超出范围')continuebreakif choice == 'Y':cls.People_can_do.add(do_sth) # 这里通过内部的cls.xxx对类变量进行了访问和修改print('人已经学习了这个技能')else:print("明白了!人不会做这个事情")else:print('人会做这个事情')@staticmethoddef introduction():print('人:哺乳动物,属于脊椎动物亚门,胎生')obj1 = People('侯震宇', 28)People.ask_do(input('请输入你想知道的人是否会做这个事情:'))
