Reputation: 5540
Everything in Python is an object, and almost everything has attributes and methods. Now, according to Object Oriented Programming, every object created in Python must be an instance of a common parent class. However, this logic just doesn't make sense to me.
Can someone clear this up for me?
Upvotes: 3
Views: 698
Reputation: 8437
In Python, all derive from the class type
this is why, whem creating a metaclass, we subclass type
class Meta(type):
def __new__(cls, name, bases, attrs):
<logic here>
class Foo(object):
__metaclass__ = Meta
Also:
type(object) -> type
type(type) -> type
DynamicClass = type('DynamicClass', (Foo,), {'a': 1, 'b':2})
dyn = DynamicClass()
type(dyn) -> Foo
etc, etc
Upvotes: 1
Reputation: 2989
according to Object Oriented Programming, every object created in Python must be an instance of a common parent class
This is not true. It happens that, in Objective-C, Java (and maybe C# too?), things tend to derive from a single superclass, but this is an implementation detail - not a fundamental of OO design.
OO design just needs a common-enough method to find the implementation of a method you wish to call on the object on which you wish to call it. This is usually fundamental to how the language works (C++, C#, Java, Objective-C, Python, etc all do it their own way that makes sense for their language).
In C++, this is done for static types by the linker and for dynamic types (through virtual inheritance) by a vector table -- no need for a common base class.
In Objective-C, this is done by looking up something in a hash-map on the object's class's structure, then calling a specific method to get the signature of the desired method. This code is nuanced, so everything generally derives from a single, common base-class.
Python technically shouldn't require this, but I think they've made an implementation choice to make everything be a class and every class derive from a common base class.
Upvotes: 4
Reputation: 8506
The common parent class in Python is object. In fact, although it's not mandatory in some versions, you should always declare your classes like this:
class MyClass(object):
...
Upvotes: 1
Reputation: 169
At some point in my life when I was confused about this, the following short tutorial helped me:
But if your confusion is more basic than this, then maybe you want to clarify which part of "everything is an object" you're having trouble with.
Upvotes: 0
Reputation: 81654
Well,
li = [1, 2, 3, 4]
class A:
def __init__(self):
pass
a = A()
print isinstance(a, object)
print isinstance(li, object)
print isinstance(5, object)
>> True
>> True
>> True
Upvotes: 0