python Python对象创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1164309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:37:23  来源:igfitidea点击:

Python object creation

pythonclassobject

提问by sunqiang

I am pretty new to Python world and trying to learn it.

我对 Python 世界很陌生,并试图学习它。

This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :)

这就是我想要实现的目标:我想创建一个 Car 类,它的构造函数检查输入以将对象 carName 设置为输入。我尝试通过使用 java 逻辑来做到这一点,但我似乎失败了 :)

class Car():
    carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
    def __self__(self,input):
        self.carName = input

    def showName():
        print carName

a = Car("bmw")
a.showName()

回答by sunqiang

derived from object for new-style class
use __init__to initialize the new instance, not __self__
__main__is helpful too.

派生自 object 用于新式类
用于__init__初始化新实例,也不__self__
__main__很有帮助

class Car(object):
    def __init__(self,input):
        self.carName = input

    def showName(self):
        print self.carName
def main():
    a = Car("bmw")
    a.showName()
if __name__ == "__main__":
    main()

回答by MrHus

You don't define a variable, and you use initand self. Like this:

您不定义变量,而是使用init和 self。像这样:

class Car(Object):
    def __init__(self,input):
        self.carName = input

    def showName(self):
        print self.carName

a = Car("bmw")
a.showName()

回答by MrHus

this is not correct!

这是不正确的!

class Car():
    carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
    def __self__(self,input):
        self.carName = input

the first carName is a class Variablelike static member in c++

第一个 carName 是类变量,类似于 C++ 中的静态成员

the second carName (self.carName) is an instance variable, if you want to set the class variablewith the constructor you have to do it like this:

第二个 carName (self.carName) 是一个实例变量,如果你想用构造函数设置类变量,你必须这样做:

class Car():
    carName = "" #how can I define a non assigned variable anyway like "String carName;" in java
    def __self__(self,input):
        Car.carName = input