0

I am new to Python. I have this code:

class SomeClass(OtherClass):
    name = "whatever"
    task = "nothing"

Now, I want to create a child class such that, I am able to instantiate it like this:

child = ChildClass(task = "sometask")
child.name #=> "whatever"
child.task #=> "sometask"
child2 = ChildClass()
child2.task #=> "nothing"

How can I do that?

1
  • You mean those URLs are kind of static data? Commented Apr 12, 2014 at 5:21

2 Answers 2

3

First, you need to note that you are creating class variables in SomeClass, not instance variables

class SomeClass(object):
    def __init__(self, name = "whatever", task = "nothing"):
        self.name = name
        self.task = task

Now we have designed a class, which accepts two keyword arguments with default values. So, if you don't pass values to any of them, by default whatever will be assigned to name and nothing will be assigned to task.

class ChildClass(SomeClass):
    def __init__(self, name = "whatever", task = "nothing"):
        super(ChildClass, self).__init__(name, task)

child1 = ChildClass(task = "sometask")
print child1.name, child1.task
# whatever sometask
child2 = ChildClass()
print child2.name, child2.task
# whatever nothing
Sign up to request clarification or add additional context in comments.

4 Comments

@Stoic Indeed, if it is a new style class :)
super (Python 2), super (Python 3)
alright, and I noticed that you called super on the class itself, and not the method? Is there a way to call the parent method without referencing super(ChildClass, self)? What I mean is I cannot I say: super(name, task) inside the child's __init__ ?
@Stoic In Python 2.x, that is how you should do. But in Python 3, you can simply do super().__init__(..). Please check the links given by Two-bit-Alchemist.
1

You need to overwrite its initializer (sort of like a constructor in other languages):

>>> class SomeClass:
...   name='whatever'
...   task='nothing'
...
>>> class ChildClass(SomeClass):
...   def __init__(self, name=None, task=None):
...     if name is not None:
...       self.name = name
...     if task is not None:
...       self.task = task
...
>>> child = ChildClass(task='sometask')
>>> child.name
'whatever'
>>> child.task
'sometask'
>>> child2 = ChildClass()
>>> child2.task
'nothing'

Comments

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.