2

Lets say this is my code:

class Cat: def __init__(self): self.purs = True self.hasFur = True class HairlessCat(Cat): def __init__(self): Cat.__init__(self) jeffery = Cat() bob = HairlessCat() 

how can I make it so jeffery has fur and bob does not (and all future Cats have fur and HairlessCats don't)?

Update: Not via changing it through HairlessCat but making it so Cat does not give any other classes inheritance towards self.hasFur.

1
  • You can't really block inheritance without bending over backwards significantly, which is rarely a good idea. The sane OO thing to do is to define both a HairyCat and a HairlessCat as distinct subspecies of Cat (or make the base cat hairless and make hairiness an explicit subspecies). With inheritance you want to go more specific in each child, not roll back previous declarations of the parent. Commented Mar 1, 2017 at 6:45

1 Answer 1

3

Use class variables. A subclass that defines a variable name similar to that contained in its base class will override the value:

class Cat: hasFur = True def __init__(self): self.purs = True class HairlessCat(Cat): hasFur = False 

in this case you also don't need to define __init__ for the subclass since, you don't change anything.

Any instances created from HairlessCat will have the attribute hasFur set to False and any of Cat to True.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.