python - 如何实现使用类和当前对象(self)的python类函数?

标签 python python-3.x

我知道我们可以显式地编写类的名称来获取类属性,并且当您需要该方法来获取从对象到对象更改的类属性时,那么“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/

相关文章:

python - Pandas 数据透视表排列没有聚合

javascript - 使用 csrf 在 javascript 页面上使用 Python/mechanize

用于搜索 NOT 和 AND 表达式的 Python Regex

Python包似乎忽略了我的要求

python - 正则表达式 : Efficiently matching words that are the same except for last character

python - 逻辑错误 - 给出的答案不正确

python - Django 创建帖子

python-3.x - 为什么我的程序停止响应并崩溃?

python-3.x - 名称 'split' 未定义问题

python - 使用 PyPi 时在 Python 3 代码库中支持 Python 2 的好方法是什么?