【问题标题】:How to avoid writing all the parameters (again) of a class? [duplicate]如何避免(再次)编写类的所有参数? [复制]
【发布时间】:2022-01-04 23:07:10
【问题描述】:

我正在用 Python 制作一个视频游戏,我想避免在我正在创建的每个类中编写所有 self.parameter1 = parameter 1

我在 YouTube 和 Stack Overflow 中寻找一种方法来自动化这个过程,但我一无所获。

我也有可能在创建一个包含这么多参数的类时出错?

P.S:我尝试了使用函数来自动化流程的想法,但可能是因为我是编程新手,我犯了错误,或者可能只是一个坏主意(我收到关于未解决的 @ 引用的错误987654322@, a, b, ...)。

以防万一我把我尝试过的代码留在这里:

def lazy:
    for parameter in parameters:
        return self.parameter == parameter

全局参数(abcdef

class npc:
    def __init__(self, parameters):
        lazy()

【问题讨论】:

  • 六个参数并不是很多。但是,如果这让您感到困扰,您总是可以传递一个字典。

标签: python class parameters


【解决方案1】:

你需要做的是创建一个父类。具有相同属性的类可以改为继承父类的属性。

例子:

class ExampleParentClass:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def foo(self):
        # do something


class ExampleChildClass(ExampleParentClass): # Inherits from the parent class
    def __init__(self, arg1, arg2, arg3):
        ExampleParentClass.__init__(self, arg1, arg2) # Initialize the parent class
        self.arg3 = arg3

    def it_works(self):
        """This works because the child class has the same 
           attributes as the parent class"""
        print(self.arg1)
        foo(self.arg2)

详细了解继承here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2021-06-14
    相关资源
    最近更新 更多