类属性和实例属性应用

#类的嵌套
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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值