为什么我的课不上课? 我尝试了多种解决方案,但没有一个可行。 我正在尝试上一堂课,但是对于上课我还是很陌生。请帮帮我。
class db:
def __init__(self, name, roof):
self.name = name
self.roof = roof
def add(self):
global roof
roof = "+--------------------------------------------------------+"
z = len(self.name)
x = len(self.roof) - z
for i in range(x - 4):
self.name = self.name + " "
print(self.roof)
print("|", self.name, "|")
db.add("NAME")
db.add("AGE")
db.add("COUNTRY")
print(roof)
错误:
Traceback (most recent call last):
File "c:/Users/User/Desktop/test/test.py", line 25, in <module>
db.add("NAME")
File "c:/Users/User/Desktop/test/test.py", line 15, in add
z = len(self.name)
AttributeError: 'str' object has no attribute 'name'
答案 0 :(得分:0)
您需要先初始化类对象才能调用类中的成员函数。
所以首先创建类对象
类似
_db = db('name', 'root')
然后调用成员函数
_db.add("NAME")
_db.add("AGE")
_db.add("COUNTRY")
并且类定义应如下所示
class db:
def __init__(self, name, roof):
self.name = name
self.roof = roof
def add(self, name): # Because you are calling with one parameter
global roof
roof = "+--------------------------------------------------------+"
z = len(self.name)
x = len(self.roof) - z
for i in range(x - 4):
self.name = self.name + " "
print(self.roof)
print("|", self.name, "|")