这是最佳实践类型的问题。我要访问从另一个属性和一个类的方法(也许这本身就是一种不好的做法)和我在做什么来实现这一目标是访问其他类的属性和方法的最佳实践
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这是否意味着我不应该访问其他类而不使用它的实例? 我认为这是一个继承问题,但我不能把这个概念带进我的脑海,而且我已经在书籍和教程中阅读了一些解释。
最后,我只是想能够访问一个类与另一个类的属性和方法。 谢谢
哦,我看到了,我看到的教程有更复杂的例子的继承困惑,但基本上我需要的是将父项传递给括号,然后调用父类的__init__,然后我将能够访问定义的所有属性在__init__中,当然还有它的方法,当然还有它的“公共”属性,比如任何类方法之外的属性。 这是正确的吗? – 2011-03-19 14:37:34
是的,但所有属性都是“公共”的,请参阅http://docs.python.org/tutorial/classes.html#private-variables。 “传递父项”表示您正在继承它,构造函数调用可确保您通过self.attrubute_name访问属性。如果你不调用构造函数,你仍然可以访问“colora”属性,但不能访问self.color。 – juanchopanza 2011-03-19 15:37:28