访问其他类属性和方法的最佳实践
这是一个关于最佳实践的问题。我想从一个类访问另一个类的属性和方法(也许这本身就是个坏习惯),我现在的做法是:
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里面声明他们的类属性,这是否意味着我不应该在没有使用实例的情况下访问其他类?我觉得这是继承的问题,但我就是理解不了这个概念,虽然我在书籍和教程中读到了一些解释。
最后,我只是想能够在一个类中访问另一个类的属性和方法。谢谢!
2 个回答
1
在普通方法中,绑定到 self
的属性只能通过调用这个方法时传入的实例来访问。如果这个方法从来没有通过某个实例被调用过,那么这个属性就不存在。
类属性就不一样了,它们是在类创建的时候就绑定好的。
另外,如果一个属性前面有一个下划线(_
),那么尽量不要在类外部访问它。
3
更明确地说,如果你想从铅笔中访问表格的颜色,你不需要把它放在一个方法里,但你需要先调用表格的构造函数:
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()
还有一个不相关的问题,这一行
object = pencil()
会遮盖掉Python中的“object”这个符号,这样做可能不是个好主意。