[英]Calling static method using class name - Good or Bad?
I am getting more and more familiar with static methods and class methods and I know the difference between each. 我对静态方法和类方法越来越熟悉,我知道它们之间的区别。 But I ran into a problem today where I would kind of like to reference both
self
and cls
in a method. 但是我今天遇到了一个问题,我想在一个方法中同时引用
self
和 cls
。
The only way I know how to accomplish this is to make a normal class method (not with @classmethod
, but simply with def
) and call the class with it's name explicitely like so: 我知道如何做到这一点的唯一方法是制作一个普通的类方法(不是使用
@classmethod
,而是简单地使用def
),并使用如下名称显式调用该类:
class myClass:
def __init__():
self._ser.connect('COM5')
def ask(self, message: str) -> str:
return myClass.clean_output(self._ser.query(message))
@staticmethod
def clean_output(dirty_string: str):
clean_string = dirty_string.strip().replace(chr(4))
return clean_string
This example is an over-simplified version of the philosophy. 此示例是该哲学的过度简化版本。 I would like to call a clean or parse function on data I get back, like from a serial device.
我想对返回的数据(例如从串行设备)调用清除或解析函数。 Is there any way to implement the ask method like so?:
有没有办法像这样实现ask方法?
def ask(self, message: str) -> str:
return cls.clean_output(self._ser.query(message))
Or is it ok that I'm calling it with myClass
explicitly like that? 还是可以像这样用
myClass
明确地调用它? If it is, when should programmers use @classmethod
and when is it permissible to use the class name itself? 如果是这样,程序员什么时候应该使用
@classmethod
?什么时候可以使用类名本身? Is using the @classmethod
decorator only really needed when you expect subclassing to happen? 是仅在您期望子类化发生时才真正使用
@classmethod
装饰器吗?
Just call the static method on self
: 只需对
self
调用static方法:
def ask(self, message: str) -> str:
return self.clean_output(self._ser.query(message))
It is available there too. 它在那里也可用。
Attributes on a class are always available on the instances too (provided there is no attribute on the instance itself with the same name masking it). 类的属性也总是在实例上可用(前提是实例本身上没有使用相同名称掩盖它的属性)。 Methods (be they regular, static or class methods) are no exception, they too are just attributes.
方法(它们是常规,静态或类方法)也不例外,它们也只是属性。 Their binding behaviour doesn't matter here.
它们的绑定行为在这里无关紧要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.