找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 1799|回复: 2

[求助] 大神求解:静态方法访问类属性的问题

1

主题

2

帖子

2

积分

贫民

积分
2
pandayu 发表于 2018-11-25 18:26:52 | 显示全部楼层 |阅读模式
Python 静态方法只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性。但是为何通过 类名.类属性 又可以访问呢?大神求解~!
回复

使用道具 举报

1

主题

8

帖子

8

积分

贫民

积分
8
pan1394 发表于 2018-11-27 15:29:02 | 显示全部楼层
本帖最后由 pan1394 于 2018-11-27 15:34 编辑

首先python class里有3种方法:
instance method, 须传入类实例 self
class method, 须传入类对象 cls
static method, 无须传入. 无法访问实例属性, 但类属性可以访问. 因为静态方法没法传入实例对象, 而类对象不需要传入即可直接获得. 请看代码:
  1. from dataclasses import dataclass

  2. @dataclass
  3. class Cup:
  4.     size: int = 2
  5.     price: float = 1.0

  6.     def __str__(self):
  7.         return "this cup size %2d and price %.2f"  % (self.size, self.price)

  8.     @staticmethod
  9.     def printStr():
  10.         print('any other things,no need but you can access Cup class cause Cup class is alreday exists in memory. ')
  11.         Cup.devil = 'diablo'
  12.         print("try to access Cup's args and other additional attribute : %d, %.2f, %s" % (Cup.size, Cup.price, Cup.devil))

  13.    
  14.     @classmethod
  15.     def printArgs(cls):{
  16.         print('class : %s args: %d, %.2f' % (cls, cls.size, cls.price) )
  17.         #cls.name = 'cap' #invalid syntax
  18.         #print('cls.name : %s' % cls.name)
  19.     }

  20. if __name__ == "__main__":
  21.     aCup = Cup(10, 12.3234)
  22.     print("aCup to string: %s" % aCup)
  23.     aCup.name = '杯子'
  24.     print("aCup.name : %s " % aCup.name)                        # print instance's additional attribute
  25.     Cup.name = 'Cap'
  26.     Cup.gender = 'male'
  27.     print("Cup.name: %s " % Cup.name)                           # print class new additional attribue
  28.     print("aCup.gender : %s" % aCup.gender)                     # print instance attribute extended from class
  29.     print("aCup to string after Cup.name is changed: %s" % aCup)  #notice that instance attribute name is not changed
  30.                                                                   #after class attribute name changed.                                       
  31.     Cup.printStr()
  32.     Cup.printArgs()


  33. Output:
  34. aCup to string: this cup size 10 and price 12.32
  35. aCup.name : 杯子
  36. Cup.name: Cap
  37. aCup.gender : male
  38. aCup to string after Cup.name is changed: this cup size 10 and price 12.32
  39. any other things,no need but you can access Cup class cause Cup
  40. try to access Cup's args and other additional attribute : 2, 1.00, diablo
  41. class : <class '__main__.Cup'> args: 2, 1.00
  42. 杯子



复制代码

回复 支持 反对

使用道具 举报

1

主题

2

帖子

2

积分

贫民

积分
2
pandayu  楼主| 发表于 2018-11-27 15:33:02 | 显示全部楼层
pan1394 发表于 2018-11-27 15:29
首先python class里有3种方法:
instance method, 须传入类实例 self
class method, 须传入类对象 cls

非常感谢!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表