Python 类中方法与属性的地址引用问题
类属性
类属性与实例对象的关系:
1.存在于类的空间中,不存在于实例对象空间中,实例对象只能引用,不能赋值。不过当类属性为可变对象时,实例对象可以改变类属性值,但类属性地址没有改变。
2.
class Cat(object):
name = "Class"
c = Cat()
print(id(Cat.name),Cat.__dict__,sep='\n')
print(id(c.name),c.__dict__,sep='\n')
#结果:
2212857559984
{'__module__': '__main__', 'name': 'Class', '__dict__': <attribute '__dict__' of 'Cat' objects>, '__weakref__': <attribute '__weakref__' of 'Cat' objects>, '__doc__': None}
2212857559984
{}
#实例中没有自己的name属性,name属性是类Cat的。
类属性与子类之间的关系:
1.基类定义类属性是基类的,存在于基类空间中,子类只能引用,不存在于子类空间。
2.
class Cat(object):
name = "Class"
class BuleCat(Cat):
pass
print(id(Cat.name))
print(Cat.__dict__)
print(id(BuleCat.name))
print(BuleCat.__dict__)
#结果
1914664631216
{'__module__': '__main__', 'name': 'Class', '__dict__': <attribute '__dict__' of 'Cat' objects>, '__weakref__': <attribute '__weakref__' of 'Cat' objects>, '__doc__': None}
1914664631216
{'__module__': '__main__', '__doc__': None}
实例对象属性
实例对象属性与类的关系
1.实例对象属性在实例对象空间中,类空间没有,类也无法访问。
2.
class Cat(object):
def __init__(self,name):
self.name = name
c = Cat("Bob")
print(Cat.__dict__)
print(c.__dict__)
#结果
{'__module__': '__main__', '__init__': <function Cat.__init__ at 0x000002CA361AB130>, '__dict__': <attribute '__dict__' of 'Cat' objects>, '__weakref__': <attribute '__weakref__' of 'Cat' objects>, '__doc__': None}
{'name': 'Bob'}
方法地址
类与对象之间
1.类中的普通方法是属于类的,存在于类空间中。但是实例对象会拷贝一份方法,但不存在于实列空间里。可能是为了不影响类中的方法本体。
2.
class Cat(object):
def func(self):
return None
c = Cat()
d = Cat()
print("Cat--->",id(Cat.func))
print("c--->",id(c.func))
print("d--->",id(d.func))
print("Cat--->",Cat.__dict__)
print("c--->",c.__dict__)
print("d--->",d.__dict__)
#结果
Cat---> 1763845058864
c---> 1763847972736
d---> 1763847973888
Cat---> {'__module__': '__main__', 'func': <function Cat.func at 0x0000019AAD5BB130>, '__dict__': <attribute '__dict__' of 'Cat' objects>, '__weakref__': <attribute '__weakref__' of 'Cat' objects>, '__doc__': None}
c---> {}
d---> {}
父类与子类之间
1.父类方法是父类的,存在父类空间中,子类单纯引用,不拷贝,子类命名空间也没有该方法。
2.
class Cat(object):
def func(self):
return None
class BlueCat(Cat):
pass
print("Cat--->",id(Cat.func))
print("Cat--->",Cat.__dict__)
print("BlueCat--->",id(BlueCat.func))
print("BlueCat--->",BlueCat.__dict__)
#结果
Cat---> 2697022124336
Cat---> {'__module__': '__main__', 'func': <function Cat.func at 0x00000273F30BB130>, '__dict__': <attribute '__dict__' of 'Cat' objects>, '__weakref__': <attribute '__weakref__' of 'Cat' objects>, '__doc__': None}
BlueCat---> 2697022124336
BlueCat---> {'__module__': '__main__', '__doc__': None}

浙公网安备 33010602011771号