class MyClass:
django = 'Django框架'
def __init__(self, x, y):
self.x = x
self.y = y
def my_method(self):
pass
# 获取自定义属性和方法
custom_attrs = [attr for attr in MyClass.__dict__ if not attr.startswith('__')]
custom_methods = [method for method in dir(MyClass) if callable(getattr(MyClass, method)) and not method.startswith('__')]
print(custom_attrs) #输出['django', 'my_method']
从输出结果来看,通过类名.__dict__的方式,只能拿到:
['django', 'my_method']
说明类的属性中不包含对象属性;
为了进一步验证,打印下dir(MyClass)
class MyClass:
django = 'Django框架'
def __init__(self, x, y):
self.x = x
self.y = y
def my_method(self):
pass
my=MyClass(1,2)
print(dir(MyClass)) # 输出结果如下
'''
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'django', 'my_method']
'''
确实不包含对象属性self.x和self.y;
接着看看对象自定义属性
class MyClass:
django = 'Django框架'
def __init__(self, x, y):
self.x = x
self.y = y
def my_method(self):
pass
my_obj = MyClass(1, 2)
# 获取自定义属性和方法
custom_attrs = [attr for attr in my_obj.__dict__ if not attr.startswith('__')]
custom_methods = [method for method in dir(my_obj) if callable(getattr(my_obj, method)) and not method.startswith('__')]
print(custom_attrs) # ['x', 'y']
print(custom_methods) # ['my_method']
可以看到对象没有打印django,所以对象和类属性django不在同一块内存空间
class MyClass:
django = 'Django框架'
def __init__(self, x, y):
self.x = x
self.y = y
def my_method(self):
pass
my_obj = MyClass(1, 2)
setattr(my_obj,'django','flask框架')
print(MyClass.django) # Django框架
print(my_obj.django) # flask框架
但是对象可以在自己的内存空间拿到django的引用重新赋值个新的数据.