方法作为具有自参数的参数

2024-04-20 02:10:31 发布

您现在位置:Python中文网/ 问答频道 /正文

不管命名约定是什么类的一部分,它只是一个测试运行。你知道吗

我需要一些关于OOP继承的帮助,我创建了一个由学生、老师和校长组成的类。我的目标是让校长能够增加员工。问题是我只想使用for循环来获取名称,然后将该方法作为主体对象的属性传递。我可以在没有self参数的情况下使用类输入来完成它。有人能告诉我吗 这里发生了什么,我怎么能用self来解决这个问题。我删除了名字中的输入,这样我的问题就不会被关闭

class Input:
     def count():
        cnt = []
        for i in range(4):
            name = ('Enter name here: ')
            cnt.append(name)
        return cnt


class Student:
    def __init__(self,name,lastname):
        self.name = name
        self.lastname = lastname

class StudentCouncil(Student):
    def __init__(self, name, lastname, tenure):
        super().__init__(name,lastname)
        self.tenure = tenure


class Principal(StudentCouncil):
    def __init__(self, name, lastname, tenure,employees=None):
        super().__init__(name,lastname,tenure)
        if employees is None:
            self.employees = []
        else:
            self.employees = employees

    def display(self):
        for names in self.employees:
            print(names,end=' ')




count = Input.count()
tij = Principal('Mike','Thoma','3',count)
tij.display()

Tags: nameinselfforinputinitdefcount
2条回答

如果countInput的全部内容,只需将其设置为函数:

def input_names():
    cnt = []
    for i in range(4):
        name = ('Enter name here: ')
        cnt.append(name)
    return cnt

如果您想要某种类型的可配置输入类型,那么您想要在其实例上运行count,您需要self

class Input:
     def count(self):
        cnt = []
        for i in range(self.num_names):  # if we need some configuration
            name = ('Enter name here: ')
            cnt.append(name)
        return cnt

否则,做这件事的犹太方式是使用staticmethod装饰器:

class Input:
     @staticmethod
     def count():
        cnt = []
        for i in range(4):
            name = ('Enter name here: ')
            cnt.append(name)
        return cnt

当前代码将与当前使用的代码一样工作,Input.count(),但如果实例化输入,Input().count()将引发异常。staticmethod修饰符确保这个方法可以安全地直接调用类或该类的实例。你知道吗

如果方法采用self参数,则需要创建类的实例。所以应该是:

class Input:
     def count(self):
        cnt = []
        for i in range(4):
            name = input('Enter name here: ')
            cnt.append(name)
        return cnt

然后你会做:

myinput = Input()
count = myinput.count()

您的count()方法没有使用self的任何属性,因此目前不需要这样编写。但你可能想重新定义它如下:

class Input:
    def __init__(self, howmany):
        self.howmany = howman

    def count(self):
        return [input('Enter name here: ') for _ in range(self.howmany)]

myinput = Input(4)
count = myinput.count()

相关问题 更多 >