Python对象创建

问题描述:

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

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

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

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 :)

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()


源自新式样式的物件类

使用 __ init __ 初始化新实例,而不是 __ self __

__ main __ 也是有用的

derived from object for new-style class
use __init__ to initialize the new instance, not __self__
__main__ is helpful too.

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()