具有定义的函数的类将无法正确调用

时间:2019-09-15 18:06:44

标签: python

问题在标题中注明。与往常一样,这可能是一个细节问题,但仍然可以得到任何帮助。

#  create a supervilan class

class supervilan:
     size = ""
     color = ""
     powers = ""
     weapons = ""
     special_ability = ""

     def customs(self):
         print(self.name + " has a supercool and technologic advanced suit.")

     def organic_gear(self, gear):
        print(self.name + " use they´re" + gear + " with mastery and precision!")

我减少了以下便利方法:

# objects

Dracula = supervilan()
Dracula.size = "2.12cm"
Dracula.color = "white"
Dracula.organic_gear("Astucy")

Chimical = supervilan()
Chimical.size = "2.30cm"
Chimical.color = "Caucasian"


Dracula.organic_gear()
Chimical.customs()

2 个答案:

答案 0 :(得分:1)

首先,您应该了解OOPs概念的基础知识,以使用类和实例。

由于要创建具有不同属性(大小,颜色等)的supervilan类的不同实例,因此必须在初始化类的实例时使它们成为实例变量而不是class并设置默认值。

class supervilan:
     def __init__(self, name='', size='', color='', powers='', weapons='', special_ability=''):
         self.name = name
         self.size = size
         self.color = color
         self.powers = powers
         self.weapons = weapons

     def customs(self):
         print(self.name + " has a supercool and technologic advanced suit.")

     def organic_gear(self, gear):
         print(self.name + " use they´re" + gear + " with mastery and precision!")

现在您可以创建具有不同属性值的类的不同实例

Dracula = supervilan("Dracula", "2.12cm", "white")


Chimical = supervilan("Chimical", "2.30cm", "Caucasian)

答案 1 :(得分:1)

位置参数是放在函数括号中的值(例如:function(arg1,arg2))。当定义函数时,organic_gear函数需要两个位置参数(organic_gear(self,gear))。但是,在您的代码中,您调用了organic_gear却没有指定“ self”或“ gear”是什么,这就是为什么出现此错误消息的原因。可能还有其他错误或样式改进需要更正,但我会将其留给精通python类的人们。