1

Basically I'm trying to do something like this:

class A:
    some_field = None # that is the field which should have 123 value

    # what needs to be here?

class B(A(123)):
    pass

class C(A(456)):
    pass

I want one base class A. And I want children B and C to be able to pass arguments to it like that A(123).

And for example if I do B.some_field I should get 123

How can I do that?

2 Answers 2

3

unutbu's answer is correct. I'd just like to point out that you can even do this stuff dynamically...

def make_class(base, value):
    class NewClass(base):
        some_field = value
    return NewClass

class A(object):
    some_field = None

B = make_class(A, 123)
C = make_class(A, 456)

And actually, this one is important enough that python actually has a builtin to do it:

class A(object):
    some_field = None

B = type('B', (A,), {'some_field': 123})

type takes 3 arguments -- The name of the class, a tuple of the base classes and a dictionary of class attributes.

Sign up to request clarification or add additional context in comments.

Comments

2

If you define B and C like this:

class B(A):
    some_field = 123

class C(A):
    some_field = 123    

then:

In [147]: B.some_field
Out[147]: 123

By the way, A(123) would pass 123 to A.__init__. It would not set some_field.

Also, in a class definition,

class B(...)

The stuff in parentheses must be a class or a comma-separated list of classes (or, in Python3, metaclass=SomeMetaClass). It can not be an instance of a class. So

class B(A(123))

is a definite no-no.


In response to the comment: You could use the A.__new__ method to return a class:

class A(object):
    some_field = None 
    def __new__(cls, val):
        cls.some_field = val
        return cls

class B(A(123)): pass

then

In [161]: B.some_field
Out[161]: 123

But this is a non-standard use of __new__ since usually it is used to return an instance of A. When it does not return an instance of A, then A.__init__ is not called.

Instead of using a class A it would be more understandable to use a class factory:

class B(make_class(123)): ...

as you mentioned in the comment below.

1 Comment

I understand that the stuff in parentheses must be a class, but I can do def A(some_field): return make_class(SomeBase, some_field) and then class B(A(123)) would be perfectly valid. I just need some syntactic sugar. Wondered if I somehow could use a class instead of a method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.