Python 为什么我们更喜欢使用self.method()而不是Class.method(self)
例如,对于某些类:Python 为什么我们更喜欢使用self.method()而不是Class.method(self),python,oop,inheritance,Python,Oop,Inheritance,例如,对于某些类: class Class(object): def __init__(self): pass def something(self): # yes I know this could be static print("something") 和实例 instance = Class() 以下两项在技术上均有效: instance.something() # normal Class.something(in
class Class(object):
def __init__(self):
pass
def something(self): # yes I know this could be static
print("something")
和实例
instance = Class()
以下两项在技术上均有效:
instance.something() # normal
Class.something(instance) # but also technically valid
为什么首选第一个用例,是否有明确的理由?我可以想到一些例子,比如迭代实例和调用方法,但我也可以想到一些例子,在这些例子中,当我使用的类的显式引用可见时,解释代码可能会更容易
如果之前已经回答过,请道歉。我找不到它,这可能是因为我在措辞上有困难
Class.something(instance)
从特定类获取方法self.something()
使用该实例的类,而该实例不一定是同一个类
如果你不得不继续使用类名,你也会重复很多次
标题使用self
,表示方法中的代码。比较以下示例的输出:
class Animal:
def make_sound(self):
print('General nature sounds')
def startle(self):
self.make_sound()
def pet(self):
Animal.make_sound(self)
class Dog(Animal):
def make_sound(self):
# overrides Animal.make_sound()
print('Bark!')
dog = Dog()
dog.startle() # prints "Bark!"
dog.pet() # prints "General nature sounds"
Animal.make_sound(self)
工作正常,但将使用原始方法,忽略Dog.make_sound()的新实现
对于在其他地方引用实例的情况,请考虑接受类或子类:
的情况。
因此我们有了一个新的Animal
子类,groom\u pet()
可以接受任何Animal
实例,因为子类也将有相同的方法。但是pet.starte()
将调用正确的make_sound()
实现,而Animal.make_sound()
将再次绕过正确的实现
对于实例上的绑定方法,很少使用unbound类方法。有时使用这种方法是有原因的;特别是如果您希望绕过父类方法(因此不使用super().method()
),或者如果您希望提高性能并避免查找属性和在紧循环中绑定方法
因为这种情况很少见,也很特殊,所以您希望坚持使用正常的习惯用法,因为这有助于您自己和其他读者理解您的代码。不要让那些读者感到惊讶。因为Class.method()
将您绑定到该类,并且您不能再重写该方法。您的标题和问题正文差异很大。我很想看一个使用Class.method(self)的示例
将使代码更容易理解。@模糊如果通过在对象之间重复调用方法将对象的iterable简化为该对象的单个实例,这可能是合理的。它将允许reduce(MyClass.some\u method,some\u iterable)
@Blurp哦,当然,我只是随口吐痰:)
class Cat(Animal):
def make_sound(self):
print('Meouw!')
def groom_pet(pet):
pet.startle()
Animal.make_sound(pet)
groom_pet(Cat()) # prints "Meouw", then "General nature sounds"