Python basics-class
All object-oriented languages have classes.
Today, I will share with you a little bit about classes in Python, focusing on comparison with classes in C ++.
In C ++, the parent class is called superclass in Python)
Create class
class Person: def setName(self, name): self.name = name def getName(self): return self.name def greet(self): print "Hello, world! I'm %s. " % self.name
This keyword in C ++, called self in Python
It seems that the self keyword is more vivid.
Binds a feature to a common function.
>>>class Class: def method(self): print 'I have a self!'>>>def function(): print "I don't...">>>instance = Class()>>>instance.method()I have a self!>>>instance.method = function>>>instance.method()I don't...
Private
Python does not have a private keyword. Whether it is a method change or a feature, add a Double underline before the name:
class Secretive: def __inaccessible(self): print 'Bet you can't see me...'
Specify the superclass
That is, the parent class and inheritance in C ++. The colon is not used here, but the superclass are written in the brackets behind the subclass:
class Filter: def init(self): self.blocked = []class SPAMFilter(Filter): def init(self): self.blocked = ['SPAM']
Check inheritance
As far as I know, there is no direct method in C ++ to determine whether two classes have parent-child relationships.
There are built-in methods in Python. The issubclass function:
>>>issubclass(SPAMFilter, Filter)true>>>issubclass(Filter, SPAMFilter)false
The only thing to note is that the first parameter is a subclass and the second parameter is a superclass.
Check whether an object is an instance of a class.
Isinstance method. The first parameter is the instance, and the second parameter is the class name.
Multiple superclasses
That is, the multiple inheritance mentioned in C ++, that is, several classes are written in parentheses, separated by commas.