Python - Class

Card Puncher Data Processing

About

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.

Creation

Class keyword

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()

Dynamic

With the type function, you can create class dynamically, see Python Type - Dynamic Class.

Factory

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

Properties

Class

the __class__ attribute

Name

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:

  • as name: myMethod
  • as fully qualified name: foo.bar.Myclass.myMethod

See also:

  • PEP 3155, Qualified name for classes and functions.

Import

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.

Call

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.

Inheritance

See Python - Class Inheritance

Method

Static

@staticmethod
def staticMethod(par1, par2):

Class

@classmethod
def classMethod(par1, par2):

Add a method

def echo(self):
          print('foo')
          
MyClass.echo = echo
hasattr(MyClass, 'echo')
True

Type

print(type(myClass))
<type 'type'>

Attribute

Accessing attributes of our objects is made using dot notation.

hasattr(ClassName, 'attribute_name')

Modification

You can change classes by using two different techniques:





Discover More
Card Puncher Data Processing
Metaclass

A metaclass is a class that create a class The main purpose of a metaclass is to change the class automatically, when it's created. The main use case for a metaclass is creating an API. See 3115PEP...
Card Puncher Data Processing
Python - Data Type

data (type|structure) in Python of a name generally a variable objecttypeintsstringsfunctionsclassesclass - an integer is a positive or negative whole number. float booleans (True...
Card Puncher Data Processing
Python - Grammar (Package | Module)

in Python On a file system: package are the directories and modules are the files within this directories. what ?? Python predecessor ABC_(programming_language)ABC. Python_syntax_and_semantics...
Card Puncher Data Processing
Python - Integer

in Python int is the class that creates integer objects
Card Puncher Data Processing
Python - Name

in Python Names (refer to|are pointer for) objects. Names are introduced by name binding operations such as during the def process. targets that are identifiers if occurring in an assignment,...
Card Puncher Data Processing
Python - Object

in Python. In Python everything is an object including: modules, classes and functions Comparing objects of different types is legal. The outcome is deterministic but arbitrary: the types...
Card Puncher Data Processing
Python - String (str type)

in Python A string literal is a sequence data type. Strings in Python are: sequence with characters as elements Each character in a string has a subscript or offset (id). The number starts at...
Card Puncher Data Processing
Python Package - Module

On a file system, package are the directories and modules are the files within this directories. A module is a file that contains structure definitions including : variables class and functions....
Card Puncher Data Processing
Python Type - Dynamic Class

With the three arguments of the type function, you can create dynamically a new class (ie a type object). type is a class that creates class objects...



Share this page:
Follow us:
Task Runner