MudBytes
» MUDBytes Community » Language Discussions » Python » Classes & Inheritance
Pages: << prev 1 next >>
Classes & Inheritance
Confuto
Conjurer






Group: Members
Posts: 113
Joined: Nov 1, 2008

Go to the bottom of the page Go to the top of the page
#1 Posted Nov 1, 2009, 6:31 pm

I think I found a solution to this a while ago, promptly forgot it and now can't remember where I found it. In any case, here's the issue:
Code (text):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> class A:
	def __init__(self):
		self.v1 = 1
		self.v2 = 2
 
 
>>> class B(A):
	def __init__(self):
		self.v2 = 4
		self.v3 = 3
 
 
>>> c = B()
>>> c.v3
3
>>> c.v2
4
>>> c.v1
 
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    c.v1
AttributeError: B instance has no attribute 'v1'
>>> 

I can see why this is happening - B's init is overwriting A's completely. Is there a convenient way around this, so that I can leave v1 untouched in B while overwriting v2 and adding v3?

EDIT: Typo :(

Last edited Nov 1, 2009, 6:32 pm by Confuto
Idealiad
Sorcerer




Group: Members
Posts: 258
Joined: Jan 28, 2007

Go to the bottom of the page Go to the top of the page
#2 Posted Nov 1, 2009, 6:43 pm

I think you want something like this:

Code (text):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
class A(object):
    def __init__(self):
        self.v1 = 1
        self.v2 = 2
 
 
class B(A):
    def __init__(self):
        super(B, self).__init__()
        self.v2 = 4
        self.v3 = 3
 
c = B()
print c.v3, c.v2, c.v1
 
>C:\Python25\pythonw -u "testClass.py"
3 4 1
>Exit code: 0
 


Note that you need to explicitly declare A as a child of object for super() to work correctly.

Orrin
Sorcerer






Group: Moderators
Posts: 286
Joined: Aug 26, 2008

Go to the bottom of the page Go to the top of the page
#3 Posted Nov 1, 2009, 6:59 pm

What about:
Code (text):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
>>> class A(object):
...     def __init__(self):
...             self.v1 = 1
...             self.v2 = 2
...
>>> class B(A):
...     def __init__(self):
...             super(B, self).__init__()
...             self.v2 = 4
...             self.v3 = 3
...
>>> c = B()
>>> c.v3
3
>>> c.v2
4
>>> c.v1
1
>>>
 


Edit: Ninja'd!
.........................
Developer, Maiden Desmodus
MudGamers - bringing the best of MUDs and online text gaming to your browser.
My Blog

Last edited Nov 1, 2009, 7:01 pm by Orrin
Confuto
Conjurer






Group: Members
Posts: 113
Joined: Nov 1, 2008

Go to the bottom of the page Go to the top of the page
#4 Posted Nov 1, 2009, 7:50 pm

Perfect! Thank you both.

Pages:<< prev 1 next >>

Valid XHTML 1.1! Valid CSS!