|
本帖最后由 pan1394 于 2018-11-27 15:34 编辑
首先python class里有3种方法:
instance method, 须传入类实例 self
class method, 须传入类对象 cls
static method, 无须传入. 无法访问实例属性, 但类属性可以访问. 因为静态方法没法传入实例对象, 而类对象不需要传入即可直接获得. 请看代码:
- from dataclasses import dataclass
- @dataclass
- class Cup:
- size: int = 2
- price: float = 1.0
- def __str__(self):
- return "this cup size %2d and price %.2f" % (self.size, self.price)
- @staticmethod
- def printStr():
- print('any other things,no need but you can access Cup class cause Cup class is alreday exists in memory. ')
- Cup.devil = 'diablo'
- print("try to access Cup's args and other additional attribute : %d, %.2f, %s" % (Cup.size, Cup.price, Cup.devil))
-
- @classmethod
- def printArgs(cls):{
- print('class : %s args: %d, %.2f' % (cls, cls.size, cls.price) )
- #cls.name = 'cap' #invalid syntax
- #print('cls.name : %s' % cls.name)
- }
- if __name__ == "__main__":
- aCup = Cup(10, 12.3234)
- print("aCup to string: %s" % aCup)
- aCup.name = '杯子'
- print("aCup.name : %s " % aCup.name) # print instance's additional attribute
- Cup.name = 'Cap'
- Cup.gender = 'male'
- print("Cup.name: %s " % Cup.name) # print class new additional attribue
- print("aCup.gender : %s" % aCup.gender) # print instance attribute extended from class
- print("aCup to string after Cup.name is changed: %s" % aCup) #notice that instance attribute name is not changed
- #after class attribute name changed.
- Cup.printStr()
- Cup.printArgs()
- Output:
- aCup to string: this cup size 10 and price 12.32
- aCup.name : 杯子
- Cup.name: Cap
- aCup.gender : male
- aCup to string after Cup.name is changed: this cup size 10 and price 12.32
- any other things,no need but you can access Cup class cause Cup
- try to access Cup's args and other additional attribute : 2, 1.00, diablo
- class : <class '__main__.Cup'> args: 2, 1.00
- 杯子
复制代码
|
|