Calculate the area live in the house
Longhand
class Room:
def __init__(self,name,owner,width,length,heigh):
self.name=name
self.owner=owner
self.width=width
self.lenth=length
self.heigh=heigh
def cal_area(self):
print('%s 住的 %s 总面积为 %s' %(self.owner,self.name,self.heigh*self.width))
r1=Room('别墅','憨憨',100,100,100)
r2Room = ( ' Chateau ' , ' Meimei ' , 1000,1000,1000 )
r1.cal_area () # Han Han live villa total area of 10000
r2.cal_area () # Meimei live Chateau total area of 1,000,000
property wording
# Property Usage
class Room:
DEF __init__ (Self, name, owner, width, length, HEIGH):
self.name = name
self.owner = owner
self.width = width
self.lenth = length
self.heigh = HEIGH
the @Property # decorator property may be converted to the property does not need to call upon the following parentheses
DEF cal_area (Self):
Print ( ' % s% s live total area% s ' % (self.owner, the self.name, Self. * HEIGH self.width))
R1 = Room (' Home ' , ' Han Han ' , 100, 100, 100 )
R2 = Room ( ' Chateau ' , ' Meimei ' , 1000, 1000, 1000 )
r1.cal_area # Han Han live villa total area of 10000
R2. cal_area # Mei Mei lived in a large villa with a total area of 1,000,000
Class method (a classmethod)
class Room:
tag=1
def __init__(self,name,owner,width,length,heigh):
self.name=name
self.owner=owner
self.width=width
self.lenth=length
self.heigh=heigh
@property
def cal_area(self,):
return self.heigh*self.width
def test(self,):
print('from test',self.name)
@classmethod # 变为了类方法
deftell_info (CLS):
Print (CLS)
Print ( ' ----> ' , cls.tag)
# DEF tell_info (Self):
# Print ( '---->', self.tag)
Print (Room.tag ) # . 1
# R1 = Room ( 'Home', 'Han Han', 100,100,100)
# Room.test ( 'test')
# Room.tell_info (R1) # ---->. 1
Room.tell_info () # - -> 1 has cls do not need to instantiate an object of
Static method
class Room: tag=1 def __init__(self,name,owner,width,length,heigh): self.name=name self.owner=owner self.width=width self.lenth=length self.heigh=heigh @property # 静态属性 def cal_area(self,): return self.heigh*self.width def test(self,): print('from test',self.name) @classmethod # 变为了类方法 def tell_info(cls): print(cls) print('---->', cls.tag) @staticmethod # 静态方法只是名义上归属性管理,不能使用类变量和实例变量,是类的工具包 def wash_body(a,b,c): print('%s %s %s 正在洗澡 '%(a,b,c)) def test(x,y,z): print(x,y,z) Room.wash_body('k','l','o') # k l o 正在洗澡 r1=Room('别墅','憨憨',100,100,100) r1.wash_body('k','l','o') # k l o 正在洗澡 Room.test('k','l','o') # k l o r1.test('k','l','o') # 报错了 不能这样调用 因为test 不是静态方法