2011-03-19 85 views
0

这是最佳实践类型的问题。我要访问从另一个属性和一个类的方法(也许这本身就是一种不好的做法)和我在做什么来实现这一目标是访问其他类的属性和方法的最佳实践

class table(): 
    def __init__(self): 
     self.color = 'green' 
    colora = 'red' 

    def showColor(self): 
     print('The variable inside __init__ is called color with a value of '+self.color) 
     print('The variable outside all methos called colora has a value of '+colora) 

class pencil(table): 
    def __init__(self): 
     print('i can access the variable colora from the class wtf its value is '+table.colora) 
     print('But i cant access the variable self.color inside __init__ using table.color ') 

object = pencil() 
>>> 
i can access the variable colora from the class wtf its value is red 
But i can't access the variable self.color inside __init__ using table.color 
>>> 

正如你可以看到我正在做一个实例在课堂上定义的铅笔,我使用符号从一个班级继承到另一个班级。

我已经读过无处不在的人声明他们的类属性init这是否意味着我不应该访问其他类而不使用它的实例? 我认为这是一个继承问题,但我不能把这个概念带进我的脑海,而且我已经在书籍和教程中阅读了一些解释。

最后,我只是想能够访问一个类与另一个类的属性和方法。 谢谢

回答

3

更explixitly,如果你想从铅笔访问table.color,你不需要包装在一个方法,但你需要调用表构造函数首先:

class table(): 

    colora = 'red' 
    def __init__(self): 
     self.color = 'green' 
     print 'table: table.color', self.color 
     print 'table: table.color', table.colora 

class pencil(table): 

    def __init__(self): 
     table.__init__(self) 
     print 'pencil: table.colora', table.colora 
     print 'pencil: pencil.color', self.color 
     print 'pencil: pencil.colora', pencil.colora 

obj = pencil() 

另一个无关的问题,这条线

对象=铅笔()

隐藏着蟒蛇“对象”的象征,极有可能不是一个好主意。

+0

哦,我看到了,我看到的教程有更复杂的例子的继承困惑,但基本上我需要的是将父项传递给括号,然后调用父类的__init__,然后我将能够访问定义的所有属性在__init__中,当然还有它的方法,当然还有它的“公共”属性,比如任何类方法之外的属性。 这是正确的吗? – 2011-03-19 14:37:34

+1

是的,但所有属性都是“公共”的,请参阅http://docs.python.org/tutorial/classes.html#private-variables。 “传递父项”表示您正在继承它,构造函数调用可确保您通过self.attrubute_name访问属性。如果你不调用构造函数,你仍然可以访问“colora”属性,但不能访问self.color。 – juanchopanza 2011-03-19 15:37:28

1

在正常方法中绑定到self的属性只能通过调用该方法时作为self传递的实例访问。如果该方法从未通过实例调用过,则该属性不存在。

类属性的不同之处在于它们在创建类本身时被绑定。

另外,如果一个属性以单个下划线开头(_),那么如果可以帮助的话,绝对不要在类之外访问它。

+0

哦,好吧,所有的属性,我想从外部的类我需要首先“发布”他们调用一个方法,返回他们的权利? – 2011-03-19 06:59:26

+0

是不是'_'用来表示在从模块导入*'执行'时不会导入''? – user225312 2011-03-19 07:00:11

+1

@Guillermo:“创造它们”是一种更准确的观察方式。 – 2011-03-19 07:03:40