简体   繁体   中英

How to create base class with type in python that overrides a variable?

Assume this example:

class A(object):
    def add(self, number):
        self.n += number

 B = type("B", (A,), {"n":3})
 b = B()
 b.add(5)
 b.n

This code works for me and returns a bn = 8 or bn=3 after object creation, but if the class A is changed to

class A(object):
    def__init__(self):
        self.n = 0
    def add(self, number):
        self.n += number
 B = type("B", (A,), {"n":3})
 b = B()
 b.add(5)
 b.n

In this case the bn is only 5, after object creation it seems that the n is taken from the base class and not from the newly created class. Is there a way to have the n object overwritten at creation time of object B ?

The dictionary passed as third argument to type are the class members. That is, your type invocation is equivalent to:

class B(A):
    n = 3

A.__init__ is inherited, and it adds an instance variable. Instance variables shadow class variables, so bn starts out as 0 (while Bn is indeed 3).

Note that the inheritance is irrelevant, the code below shows the same behavior:

class B(object):
    n = 3

    def __init__(self):
        self.n = 0

    def add(self, number):
        self.n += number

@delnan gives an explanation of why this is happening.

The following shows how you can do what you're trying to do:

class A(object):
    def __init__(self):
        self.n = 0
    def add(self, number):
        self.n += number

def create_B(initial_n):
  class B(A):
    def __init__(self):
      self.n = initial_n
  return B

B = create_B(3)
b = B()
b.add(5)
print b.n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM