本文介绍了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()
这篇关于Python对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!