我知道我们可以显式地编写类的名称来获取类属性,并且当您需要该方法来获取从对象到对象更改的类属性时,那么“self”作为第一个参数应该可以正常工作。
但是,我真的不知道如何以一种奇特的方式做到这两点。
class Alpha:
base = 0
round = 360
def __init__(self, radius: float, angel: float = 0):
self.radius = radius
self.angel = angel
def spin(self, angel: float = 0, K: int = 0):
# need to use both 'base' & 'self.radius'
# should I use it like that?
if self.radius is not Alpha.base and angel is not None:
self.angel = (angel + (360 * K))
像我一样使用可以吗?
最佳答案
如果你不打算子类化它,你的方法就很好
但是,如果您要对其进行子类化,请使用以下内容:
class Alpha:
base = 0
round = 360
def __init__(self, radius: float, angel: float = 0):
self.radius = radius
self.angel = angel
def spin(self, angel: float = 0, K: int = 0):
# need to use both 'base' & 'self.radius'
# should I use it like that?
if self.radius is not self.__class__.base and angel is not None:
self.angel = (angel + (360 * K))
self.__class__
返回类而不是对象
class Alpha:
base = 0
round = 360
def __init__(self, radius: float, angel: float = 0):
self.radius = radius
self.angel = angel
def spin(self, angel: float = 0, K: int = 0):
# need to use both 'base' & 'self.radius'
# should I use it like that?
if self.radius is not self.base and angel is not None:
self.angel = (angel + (360 * K))
也可以工作,因为类变量被带入对象中,这对于没有 self 作为第一个的函数不会按预期工作
class foo:
def bar(foobar):
return foobar * 2
foobar = foo()
foobar.bar("foo")
这会导致
类型错误:bar()需要1个位置参数,但给出了2个
或类似错误
要防止此错误,只需添加装饰器静态方法,如下例所示:
class foo:
@staticmethod
def bar(foobar):
return foobar * 2
foobar = foo()
foobar.bar("foo")
>>> foofoo
关于python - 如何实现使用类和当前对象(self)的python类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60020365/