#类的嵌套
class parent:
def __init__(self):
self.name = "parent"
def getName(self):
print(self.name)
class child:
def __init__(self):
self.name = "child"
def getName(self):
print(self.name)
p = parent()
p.getName()
c = p.child()
c.getName()
输出为:
parent
child
"""
类属性和对象属性
当对象的类属性没有修改时,会和类共用类属性。
当对对象的类属性进行修改,则对象会保存该属性,不再和类共用一个类属性。
"""
class People(object):
money = 1000
def __init__(self, name, age, gender=1):
self.name = name
self.age = age
self.gender = gender
print(id(self.money))
print(id(People.money))
student1 = People("zhangsan", 20)
student2 = People("lisi", 25)
print(student1.name)
print(student2.name)
output:
2103971257872
2103971257872
2103971257872
2103971257872
zhangsan
lisi
People.money = 4
print(id(People.money))
print(id(student1.money))
print(id(student2.money))
print(People.money)
print(student1.money)
print(student2.money)
output:
1399634480
1399634480
1399634480
4
4
4
student1.money = 1
student2.money = 2
print(id(People.money))
print(id(student1.money))
print(id(student2.money))
print(People.money)
print(student1.money)
print(student2.money)
output:
1399634480
1399634384
1399634416
4
1
2
class animal:
count = 0
def __init__(self):
animal.count += 1
x = animal()
x.count
output:
1
y = animal()
y.count
output:
2
"""
当类属性和实例属性发生冲突时,如下所示的 name 属性,
此时调用test对象,会发现无法获取类属性name,得到的是实例属性name。
在对象中,查找属性时,会先从实例属性中查找,如果没找到,会转到类属
性中查找,如果还没找到,就会报错。(在实例中优先查找和修改实例属性,
然后是类属性)
"""
class Test:
name = "zhangsan"
def __init__(self):
self.name = "lisi"
test = Test()
print(Test.name)
print(test.name)
output:
zhangsan
lisi