不管是哪个类,只是一个测试运行,都不要使用命名约定。
我需要一些有关OOP继承的帮助,我创建了学生,教师和校长一类。我的目标是使校长能够增加员工。问题是我只想使用一个for循环来获取名称,然后将该方法作为主体对象的属性传递。我能够使用没有self参数的Input类做到这一点。有人可以告诉我 这是怎么回事,我该如何自我修复。我从名称中删除了输入内容,这样我的问题就不会被关闭
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()
答案 0 :(得分:3)
如果该方法采用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()
答案 1 :(得分:2)
如果您想从count
中获得Input
,只需使其成为函数:
def input_names():
cnt = []
for i in range(4):
name = ('Enter name here: ')
cnt.append(name)
return cnt
如果您想要某种可配置的Input类型,那么您想在其中的一个实例上运行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
装饰器确保此方法可以安全地直接在类上或在该类的实例上调用。