June 11th, 2005, 11:15 AM
What is the telltale indicating that one class inherited from another class?
June 11th, 2005, 11:30 AM
This is a bad example but anything that is in the first class or above the one that is inheriting can be used by the second below it
>>> class C1:
>>> class C2(C1):
>>> c1 = C1()
>>> c2 = C2()
Last edited by monkeyman23555; June 11th, 2005 at 11:33 AM.
Those people who think they know everything are a great annoyance to those of us who do.
June 11th, 2005, 12:55 PM
From the docs:
There is also an isinstance function to test if an object is an instance of a class or one of its subclasses.
Dave - The Developers' Coach
June 11th, 2005, 11:28 PM
If you are wondering when to tell if a class should inherant from anouther class, I was always taught only do it if it can pass the "is a" or "is an" test
apple is a fruit
dog is a animal
but things like this would be considered bad:
bird is a dog
grape is a apple
because everyone knows that there is no dog bird, only bird dogs..
That is just a nice easy way to tell, Thats just about the most I got out of java.
Comments on this post
June 12th, 2005, 05:19 AM
in addition to isinstance and issubclass there's also type(). You can also use obj.__class__ and cls.__bases__:
class Foo(object): pass
class Bar(object): pass
class Baz(Foo, Bar): pass
x = Baz()
for base in x.__class__.__bases__:
print base, base.__bases__
the "is a(n)" test can be good for getting the basic structure down, but the problem is that it makes you thing in terms of nouns - Car is a Vehicle.
Originally Posted by CyBerHigh
The standard use of OO in Python is known as "duck typing" because you don't care about what class an object is - if it walks like a duck and quacks like a duck it can be treated like a duck - ie: Objects which provide a particular function can be treated alike for the purpose of calling that function, even if everything else about that object is different:
So rather than thinking of "is a", you think of things in terms of common capabilities - the "can <action>" test, eg:
def foo(self): pass
return "Duck quacking"
def bar(self): pass
return "Doctor faking it"
x = Duck("donald")
y = Doctor("Who")
for elem in (x, y):
print elem, "|", elem.quack()
* Button is Selectable, Clickable, etc
* Goblin is Attackable, Converseable, etc.
* Car is Driveable, Crashable, etc
This makes you think in terms of verbs - ie: your interface.
There's also the compositional "has a" test:
* Window has a (TitleBar, MenuBar, DisplayPane, Border)
def __init__(self, parent):
self.parent = parent
pass # move all components