Object use: Class name (parameter) can be called with self
The Def _new_ (CLS) is used to create objects, but must have a return value, which is instantiated
The Def _init_ (self, parameter) initialization method, which defines the initialization value for a parameter.
Def_str_ (self) overriding the parent class Objectstr method
#sys. Getrefcount () tests how many references an object has
Import Sys
Class Student:
def sleep (self):
Print ("Sleep")
T=student ()
Print (Sys.getrefcount (t))
Construction Method:
Class A:
def __new__ (cls,name):
Return object.__new__ (CLS)
def __init__ (self,name):
Self.name=name
A=a ("Tom")
#单例
Class Singletone:
__instance=none #私有
def __new__ (CLS):
If Cls.__instance==none:
CLS.__INSTANCE=OBJECT.__NEW__ (CLS)
Return cls.__instance
Else
Return cls.__instance
S=singletone ()
Ss=singletone ()
Print (ID (s), ID (ss))
Sort objects
Class Car:
def __init__ (Self,brand=none,price=none):
Self.brand=brand
Self.price=price
def __gt__ (self, Other):
Return Self.brand.encode ("GBK") >other.brand.encode ("GBK")
def __str__ (self):
Return Self.brand+str (Self.price)
Lists=[car ("Ah Dee:", 300000), car ("The English-Philippine:", 350000), car ("Audi:", 400000)]
Lists.sort ()
Print (lists)
For I in lists:
Print (i)
Inheritance: Subclass inherits parent class, subclass can have properties and methods of parent class, reduce code redundancy
Class Person:
def __init__ (Self,name=none,age=none,sex=none):
Self.name=name
Self.age=age
Self.sex=sex
def __str__ (self):
Return "My name: {0}, my age: {1}, my gender: {2}". Format (Self.name,self.age,self.sex)
Class Music:
def __init__ (Self,piano=none):
Self.piano=piano
Class Student (Person,music):
def __init__ (Self,name=none,age=none,sex=none,score=none,piano=none):
# # Self.name=name
# Person.name=name
# Self.age = Age
# self.sex = Sex
Person. __init__ (Self,name,age,sex)
Self.score=score
Music.piano=piano
def __str__ (self):
Return "My name: {0}, my age: {1}, my gender: {2}, my score: {3}, music: {4}". Format (Self.name,self.age,self.sex,self.score,self.piano)
Stu=student ("Mary", +, ' female ', 80)
Print (STU)
Call the Parent class property method in the subclass:
1. Parent class. Properties
2 self. Properties
3 parent class. _init_ (self, parameter)
4 Super (parent class, self). _init_ (All parameters)
Multiple Inheritance: Class C (A, B): When multiple parent classes are inherited, they are separated by commas and written in parameters
Python lesson fifth, class objects, sorting, Singleton, inheritance