简体   繁体   English

在Python 3.4.0中object()不接受任何参数

[英]object() takes no parameters in Python 3.4.0

Why do I get this error when trying to run the following code? 为什么在尝试运行以下代码时出现此错误?

cObj1 = Car("Ford", "Black") TypeError: object() takes no parameters cObj1 = Car(“ Ford”,“ Black”)TypeError:object()不带参数

class Car(object):
  numwheels = 4
  def display(self):
    print("Make:", self.make)
    print("Colour:", self.colour)
    print("Wheels:", Car.numwheels)

#main program
cObj1 = Car("Ford", "Black")
cObj1.display()

This will do: 这样可以:

class Car:
    numwheels = 4
    def __init__(self, make, colour):
        self.make = make
        self.colour = colour

    def display(self):
      print("Make:", self.make)
      print("Colour:", self.colour)
      print("Wheels:", Car.numwheels)

#main program
cObj1 = Car("Ford", "Black")
cObj1.display()

OUTPUT: OUTPUT:

Make: Ford
Colour: Black
Wheels: 4

Few things with your code: 您的代码很少:

1- You don't have to inherit from object in Python implicitly. 1-您不必隐式从Python object继承。

2- You have to initialize all your instance properties before using them. 2-您必须先初始化所有实例属性,然后才能使用它们。 That is usually done inside the __init__ method. 这通常是在__init__方法内部完成的。

I really recommend you make a fast read https://docs.python.org/3/tutorial/classes.html 我真的建议您快速阅读https://docs.python.org/3/tutorial/classes.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM