Object - Class (or Struct) in Python
The difference with a standard class implementation is that in Python, Classes are objects because the class keyword will creates an object. Only a class object is capable of creating objects.
A basic class consists only of the class keyword, the name of the class, and the class from which the new class inherits in parentheses.
By convention, user-defined Python class names start with a capital letter.
Accessing attributes of our objects is made using dot notation.
class Fruit(object):
"""A class that makes various tasty fruits."""
# Member variable
myBoolean = True
# The init function is used to initialize the objects (required)
# The self argument refers to the object being created.
# It's common to use self as the first parameter
def __init__(self, name, color, flavor, poisonous):
self.name = name
self.color = color
self.flavor = flavor
self.poisonous = poisonous
def description(self):
print "I'm a %s %s and I taste %s." % (self.color, self.name, self.flavor)
def is_edible(self):
if not self.poisonous:
print "Yep! I'm edible."
else:
print "Don't eat me! I am super poisonous."
lemon = Fruit("lemon", "yellow", "sour", False)
lemon.description()
lemon.is_edible()
With the type function, you can create class dynamically, see Python Type - Dynamic Class.
Because a class is an object, you can manipulate it as any variable.
def class_factory(name):
if name == 'foo':
class Foo(object):
pass
return Foo # return the class, not an instance
else:
class Bar(object):
pass
return Bar
the __class__ attribute
The name of the class is in the __name__ attribute.
If you have a nested package named foo.bar with a class Myclass, the method myMethod on that class will have:
See also:
A qualified name lets you re-import the exact same object, provided it is not an object that is private to a local (function) namespace.
When calling the items method
my_dict.items()
Python checks to see if the dictionary my_dict has an items() method and executes that method if it finds it.
@staticmethod
def staticMethod(par1, par2):
@classmethod
def classMethod(par1, par2):
def echo(self):
print('foo')
MyClass.echo = echo
hasattr(MyClass, 'echo')
True
print(type(myClass))
<type 'type'>
Accessing attributes of our objects is made using dot notation.
hasattr(ClassName, 'attribute_name')
You can change classes by using two different techniques: