-1

I've been trying to comprehend python's implementation of OOP.

Essentially I need something which is a superclass that defines some global attributes that al l other classes use as input for their methods. Eg:

This is how i thought it should be done:

class One():
    def __init__(self, name):
         self.name = name

class Two(One):
     def __init__(self, name):    # name from class one...
         One.__init__(self, name)          
     def method_using_name_from_one(self, name_from_one):
         return name_from_one

I guess that I could do this by just declaring all the methods in class Two as in methods of class one, but I'd much prefer to have them separated. So to recap: I want the parameters for the method in class two to use the attributes declared in class One. So essentially I want to pass in an instantiated object as the parameter arguments for class Two methods.

4

1 回答 1

0

当你说

class Two(One):

一个不是 的参数class Two。这意味着类二继承自类一。换句话说,除非你重写一个方法,否则它会得到类 One 所拥有的一切。编辑:当我说这个时,我的意思是参数和函数,我不是指类的实例。既然你有:

def __init__(self, name):    # name from class one...
    One.__init__(self, name) 

self.nameclass Two.在 换句话说,你可以说...

 def method_using_name_from_one(self):
     return self.name

我建议的一件事是将您的类 One 声明更改为:

 class One(object):

这意味着它继承自对象,并不意味着它正在传递一个对象:) 这就是你的意思吗?也许我没有正确理解。

如果你想要 name 参数,One,你可以说

 def method_using_name_from_one(self, oneInstance):
     return oneInstance.name
于 2013-08-01T22:49:53.513 回答