from types import MethodType
class Screen(object):
__slots__=('_width','_height','_resolution')
# __slots__ 限定的是在之后仅仅可以创建的哪些变量,不包含一开始就创建的.如果
def runner(self):
print("hhah")
@property
def width(self):
return self._width
@width.setter
def width(self,width):
if not isinstance(width,int):
print('You should enter an integer')
else:
self._width=width
@property
def height(self):
return self._height
@height.setter
def height(self,height):
if not isinstance(height,int):
print('You should enter an integer')
else:
self._height=height
@property
def resolution(self):
return self._width*self._height
print(hasattr(Screen, '_width'))
sc = Screen()
sc.width = 1024
sc.height = 768
print(hasattr(sc, 'width'))
print(sc.resolution)
def run():
print("running")
# sc.run = MethodType(run, sc)
# sc.run()
sc.runner()
在python中子类和父类可以共享同一个方法属性(代码段存储在一个块中,引用时只是将指针指向了那里),但是,对于变量属性,子类必须是在内存区间中另创建一个区间去存储变量。