【问题标题】:How to call object initialized to a number?如何调用初始化为数字的对象?
【发布时间】:2020-01-29 08:13:28
【问题描述】:

如果我将这些函数放在一个类中,我将如何从同一个类中的另一个函数调用它们?

class Dead:
    def initial(self):
        self.amy = 1
        self.bob = 2
        self.cam = 3

    def __init__(self):
        self.initial()

    def get_number(self, number):

我怎么能调用 self.amy,作为回报得到数字 1?在 get_number 中,我想将 self.amy 添加到一个数字中以返回总和,但就像所有 amy、bob、cam 一样,可以使用 for 函数?在不完全剧透问题的情况下,我不知道如何措辞这个问题,抱歉。

【问题讨论】:

  • 为什么还需要get_number?只需从类中的其他方法执行self.amy
  • @DeepSpace idk 这正是我的老师给我们问题的方式

标签: python class variables methods numbers


【解决方案1】:

您可以更改您的 get_number 方法以改为接受成员变量名称并动态检索它。例如

class Dead:
    def initial(self):
        self.amy = 1
        self.bob = 2
        self.cam = 3

    def __init__(self):
        self.initial()

    def get_number(self, name, number):
        return getattr(self, name) + number

但是,这不仅仅是多余的。您已经可以从您的对象中访问这些变量,添加一个访问它们的方法就是无缘无故地添加一个额外的层。

class Dead:
    def initial(self):
        self.amy = 1
        self.bob = 2
        self.cam = 3

    def __init__(self):
        self.initial()

dead = Dead()
dead.amy # 1
dead.bob # 2
dead.cam # 3
dead.amy += 1 # 2

添加一个initial 方法来初始化您的成员变量也是如此。没有理由不直接在您的__init__ 中这样做。

class Dead:
    def __init__(self):
        self.amy = 1
        self.bob = 2
        self.cam = 3

添加无用的方法并没有让你的代码更好,它真的只是污染它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2013-06-27
    • 2020-04-21
    • 2016-03-11
    • 2011-07-26
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多