将 class 方法访问实例方法的最佳方法
Best way to access class-method into instance method
class Test(object):
def __init__(self):
pass
def testmethod(self):
# instance method
self.task(10) # type-1 access class method
cls = self.__class__
cls.task(20) # type-2 access class method
@classmethod
def task(cls,val)
print(val)
我有两种方法可以将 class 方法访问到实例方法中。
self.task(10)
或
cls = self.__class__
cls.task(20)
我的问题是哪一个最好,为什么?
如果两种方法不一样,那么我在什么情况下使用哪一种?
self.task(10)
绝对是最好的
首先,对于 class 个实例,两者最终将以相同的操作结束:
- __class__ 是保证 class 实例对象存在的特殊属性,是对象的 class (Ref: Python reference manual / Data model / The standard type hierarchy)
Class instances
...
Special attributes: __dict__ is the attribute dictionary; __class__ is the instance’s class
- 使用 class 实例对象调用 class 方法实际上将对象的 class 传递给方法(参考:参考手册的同一章节):
...When an instance method object is created by retrieving a class method object from a class or instance, its __self__ attribute is the class itself
但第一个更简单,不需要使用特殊属性。
class Test(object):
def __init__(self):
pass
def testmethod(self):
# instance method
self.task(10) # type-1 access class method
cls = self.__class__
cls.task(20) # type-2 access class method
@classmethod
def task(cls,val)
print(val)
我有两种方法可以将 class 方法访问到实例方法中。
self.task(10)
或
cls = self.__class__
cls.task(20)
我的问题是哪一个最好,为什么?
如果两种方法不一样,那么我在什么情况下使用哪一种?
self.task(10)
绝对是最好的
首先,对于 class 个实例,两者最终将以相同的操作结束:
- __class__ 是保证 class 实例对象存在的特殊属性,是对象的 class (Ref: Python reference manual / Data model / The standard type hierarchy)
Class instances
...
Special attributes: __dict__ is the attribute dictionary; __class__ is the instance’s class
- 使用 class 实例对象调用 class 方法实际上将对象的 class 传递给方法(参考:参考手册的同一章节):
...When an instance method object is created by retrieving a class method object from a class or instance, its __self__ attribute is the class itself
但第一个更简单,不需要使用特殊属性。