简体   繁体   English

Python类中未解决的参考

[英]Unresolved reference in Python class

This is my code: 这是我的代码:

class robot:
    def __init__(givenName,givenColor):
        self.name=givenName//error
        self.color=givenColor//error
    def intro(self):
        print("my name izz "+self.name)

r1=robot();
r1.name='tom'
r1.color='red'

r2=robot();
r2.name='blue'
r2.color='blue'
r1.intro()
r2.intro()

I am getting an error in the above commented lines. 我在上面的注释行中出现错误。 I know this question has many answers on stackoverflow but none seems to work . 我知道这个问题在stackoverflow上有很多答案,但是似乎都没有用。 the function calls self.color and self.color give the error. 函数调用self.color和self.color给出错误。

The first argument of __init__ should be self : __init__的第一个参数应该是self

def __init__(self, givenName, givenColor):
    self.name = givenName
    self.color = givenColor

Otherwise, your code will fail as self will not be accessible within the method. 否则,您的代码将失败,因为self将无法在该方法中访问。

You have 2 options to define attributes: 您有2个定义属性的选项:

Option 1 选项1

Define at initialization with __init__ as above. 如上所述,在初始化时使用__init__定义。 For example: 例如:

r1 = robot('tom', 'red')

Option 2 选项2

Do not define at initialization, in which case these arguments must be optional: 不要在初始化时定义,在这种情况下,这些参数必须是可选的:

class robot:
    def __init__(self, givenName='', givenColor=''):
        self.name=givenName
        self.color=givenColor
    def intro(self):
        print("my name izz "+self.name)

r1 = robot()

r1.givenName = 'tom'
r1.givenColor = 'red'

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

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