2015-07-09 41 views
-1

我有类的简单的例子,在python:面向对象的Python

class song: 
    def __init__(self, x): 
     print x 

bang=song(['Our whole universe was in a hot dense state,Then nearly fourteen billion years ago expansion started, wait...']) 

这工作。 但在另一本书词“对象”创建一个新的类时使用:

class song(object): 
    def __init__(self,x): 
     print x 

bang=song(['Our whole universe was in a hot dense state,Then nearly fourteen billion years ago expansion started, wait...']) 

这工作了。另外,如果目的是通过,被取代的,例如,X:

class song(x): 
    def __init__(self,x): 
     print x 

smile=song(['Our whole universe was in a hot dense state,Then nearly fourteen billion years ago expansion started, wait...']) 

它不工作(NameError: name x is not defined)。 什么特别之处object,据我所知,它甚至不是一个保留字,是不是?为什么代码与它一起工作,而与x - 不?

+4

你可能想看看[Python中继承(https://docs.python.org/2/tutorial/classes.html#inheritance),然后在[老VS新式类(HTTPS: //wiki.python。org/moin/NewClassVsClassicClass) – dhke

+0

'NameError'通常是指尝试引用不存在的内容。仅供将来参考。 – bcdan

回答

1

这不起作用,因为x正在被视为构造函数类。这意味着,基本上,为了使您的代码正常工作,x已被定义为class

当您使用object创建一个类,您使用的模板类,是空的,使一个新类型的类。使用intdict也会发生类似的情况。新类继承了该类型的属性。

由于未定义类x,所以新类不能使用x作为构造函数。因此,返回该错误。所有的

0

因为object是你继承的基础对象。 x不存在作为一个对象,因此不能从

继承你可以这样做:

class x(object): 
    def __init__(self, item) 
     self.item = item 


class song(x): 
    def print(self): 
     print(self.item) 


bang=song(['a bunch of text']) #why is this a list? 

bang.print() 

有你有它inheritance - 这么多X的让这个混乱

0

首先,你应该得到与inheritance

熟悉如图所示在其他的答案就可以说明class song(x):,如果x是对自己的一类。通过这样做,song类将继承基类x中的方法。现在

,一类声明从对象继承的原因可以追溯到python2.2。这些类声明称为:New style classes

他们有不同的对象模型,以经典的对象,并有一组不存在于经典对象的属性和功能。这方面的一些例子是@property关键字,super()方法。有关它们的区别的更多细节可以在here找到,但它在Stack Overflow上也有广泛的讨论:here

建议使用这些new style classes以使您的基类继承object类。