A simple sample with interface
import abc
country = 'China'
# Interface
class Humane(metaclass=abc.ABCMeta):
def __init__(self):
pass
@abc.abstractmethod
def conscience(self):
pass
@abc.abstractmethod
def survival(self):
pass
# Person
class Person(Humane):
# Works, but not recommend
job = "IT"
# is the key to what will object own!
def __init__(self, name, age):
self.name = name
self.age = age
def say(self):
print(self.name)
print(country)
def conscience(self):
print('conscience')
def survival(self):
print('survival')
# This will treat a method as property way to use
@property
def eat(self):
return 'eat'
# Invoked by Class
@classmethod
def commonApprochInClass(cls):
print(cls.job)
# Static method
@staticmethod
def commonApproch(name, age):
print(name + ' ' + age)
p1 = Person("John", 36)
# will print the memory path
print(p1)
# class dict, own both data properties and method properties
print(Person.__dict__)
# object dict, only has data properties
print(p1.__dict__)
print(p1.name)
print(p1.job)
p1.say()
Person.say(p1)
# @property
print(p1.eat)
# @classmethod
Person.commonApprochInClass()
Person.gender = "mail"
print(p1.gender)
print(p1.__dict__)
multiple extend
# In python, class support multiple extend
class God:
def __init__(self):
pass
def eat(self):
print('God eat')
class Animal(God):
def __init__(self, gender, color):
self.gender = gender
self.color = color
def eat(self):
print('Animal eat')
class Canidae:
def __init__(self):
pass
def eat(self):
print('Canidae eat')
class Dog(Animal, Canidae):
def __init__(self, gender, color, tail):
# super(self).__init__(gender, color)
Animal.__init__(self, gender, color)
self.tail = tail
def bark(self):
print('Bark!!')
# When a class is going to use the method/property off its parents classes,
# it will apply depth-first in Python 2.7 and breadth-first in Python 3.x.
dog = Dog('male', 'Black', 'long')
dog.eat()
print(Dog.__mro__)
Reflection
class Vehicle:
feature = 'Ugly'
def __init__(self, name, type):
self.name = name
self.type = type
def run(self):
print('Vehicle run')
def speak(self):
print('Vehicle speak')
ve = Vehicle('Car', 'small')
# hasattr is checking if a obj can invoke a attr/method
print(hasattr(ve, 'name'))
print(hasattr(ve, 'feature'))
print(hasattr(ve, 'feature111'))
print(getattr(ve, 'name'))
print(getattr(ve, 'feature'))
print(getattr(ve, 'feature111', "None"))
setattr(ve, 'newFeature', 'Beautiful')
setattr(ve, 'jump', lambda x: x + 1)
print(getattr(ve, 'newFeature', "None"))
delattr(ve, 'newFeature')
print(getattr(ve, 'newFeature', "None"))