Python: Notes (3)--object-oriented programming types and object terminology
all data stored in the program is an object . Each object has an identity, a category, and a value.
For example: a=42, the value 42 is used to create an integer object.
Most objects have properties and methods that have a lot of characteristics.
- The property is the value associated with the object.
- The method is the function that will perform certain operations on the object when called.
- Use. operator to access properties and methods.
Some descriptions of objects in Python
- The best way to check the object type is to take advantage of the built-in function isinstance (object,type)
- All objects have reference counts, and when an object's reference count is zeroed, he will be disposed of by the garbage collection mechanism.
- For immutable objects such as strings and numbers, A=b actually creates a new copy.
- Shallow copy creates a new object, but it contains values that are references to the items contained in the original object .
- deep Copy creates a new object and recursively copies all of the objects it contains. You can use the Copy.deepcopy () function to complete the work.
- All objects in Python are in the first class, meaning that all objects that can be named can be treated as data.
Demonstrate shallow and deep replication
1 #Shallow Copy2a=[1,2,[3,4]]3B=list (a)#Create a shallow copy of a4 Print(b isa)5B.append (100)6 Print(b)7 Print(a)8b[2][0]=-1009 Print(b)Ten Print(a)
"Result":
False
[1, 2, [3, 4], 100]
[1, 2, [3, 4]]
[1, 2, [-100, 4], 100]
[1, 2, [-100, 4]]
1 # Deep Replication 2 Import Copy 3 a=[1,2,[3,4]]4 b=copy.deepcopy (a)5 b[2][0] =-1006 Print(b)7print(a)
"Result":[1, 2, [ -100, 4]][1, 2, [3, 4]]
Classes and the creation of object-oriented programming classes
1 method of Object initialization2 classMyClass (object):3 def __init__(self,type):4Self.type=type5 defPrintinfo (self):6 Print(Self.name,' Age is', Self.age)7 Print(Self.name," Age is", Self.age, sep=',')8 9 TenAClass = MyClass (1) One #Assigning properties to Objects AAclass.name ='Bob' -Aclass.age=19 the #Viewing Object Properties - Aclass.name - Aclass.age - Aclass.type + #Calling Object Methods - Aclass.printinfo () + "Output" ABob Age is19 atBob,age is, 19
"A few notes":
- Notice that the
__init__
first parameter of the method is always the one that self
represents the created instance itself , so within the __init__
method, you can bind various properties to it self
, because self
it points to the created instance itself .
- a function defined in a class is only a little different than a normal function, that is, the first argument is always an instance variable,
self
and when called, it is not passed . In addition, there is no difference between a class method and a normal function, so you can still use default parameters, variable arguments, keyword arguments, and named keyword parameters.
- Unlike static languages,Python allows you to bind any data to an instance variable, which means that for two instance variables, although they are different instances of the same class, the variable names you have may be different .
Access restrictions
Description
If you want the internal properties to be inaccessible externally, you can add the name of the property to the two underscore _, in Python, the variable name of the instance begins with _ and becomes a private variable. , only internal access is available.
1 classStudent (object):2 def __init__(self, Name, score):3Self.__name=name4Self.__score=score5 6 defPrint_score (self):7 Print('%s:%s'% (self.__name, self.__score))8 defGetName (self):9 Print(self.)__name)
Description
Bob = Student (' Bob ', Bob.print_score) Bob.getname () Bob. __name#这是不允许的
"A few notes"
- In Python, a variable name, which starts with a double underscore and ends with a double underscore,
__xxx__
is a special variable that is directly accessible, not a private variable , so you can't use __name__
__score__
a variable name like this.
- There are times when you see an instance variable name that starts with an underscore, such as an
_name
instance variable that can be accessed externally, but, as you see in the rules, when you look at such a variable, it means, " although I can be accessed, but please treat me as a private variable, Do not feel free to access ".
Inheritance and polymorphism
The "Duck type" of dynamic language, which does not require a strict inheritance system, an object as long as "looks like a duck, walk like a duck", it can be regarded as a duck.
Python allows multiple inheritance, and in dynamic languages such as Python, it is not necessary to pass in the animal type. We just need to make sure that the incoming object has a run () method on it:
1 classAnimal (object):2 defRun (self):3 Print(Self.name)4 def __init__(self,name):5Self.name=name6 classDog (Animal):7 Pass8 9 deftest (animal):Ten Animal.run () One ADog = Dog ("Animal") -Test (dog)
Get object Information
1. If you want to get all the properties and methods of an object, you can use a dir()
function that returns a list that contains a string.
2. Cooperation getattr()
, setattr()
and hasattr()
, we can directly manipulate the state of an object
3. always use Isinstance () to determine the type, and you can "clean sweep" The specified type and its subclasses.
Restricting instance properties using __slots__
Python allows you to define a special variable when defining a class __slots__
to limit the attributes that the class instance can add :
1 classStudent (object):2 __slots__= ('name',' Age')#Define a property name that allows binding by using a tuple3 4>>> s = Student ()#Create a new instance5>>> S.name ='Michael' #binding Property ' name '6>>> S.age = 25#binding attribute ' age '7>>> S.score = 99#binding attribute ' score '8 Traceback (most recent):9File"<stdin>", Line 1,inch<module>Ten attributeerror: ' Student ' object has no attribute ' score '
Using @property
1. Adorner limit attribute value: A getter method into a property, just add @property
it, we can also add setter method
1 classStudent (object):2 @property3 defscore (self):4 returnSelf._score5 @score. Setter6 defscore (self, value):7 if notisinstance (value, int):8 RaiseValueError ('score must is an integer!')9 ifValue < 0orValue > 100:Ten RaiseValueError ('score must between 0 ~ 100!') OneSelf._score = value
2. Set read-only properties: only the Getter method is defined, and the setter method is not defined as a read-only property
1 classStudent (object):2 3 @property4 defBirth (self):5 returnSelf._birth6 7 @birth. Setter8 defBirth (self, value):9Self._birth =valueTen One @property A defAge (self): - return2015-self._birth
Using enum classes
1. Simply create an enumeration class
1 fromEnumImportEnum2 3Month = Enum ('Month', ('Jan','Feb','Mar','APR',' May','June','Jul',' the','Sep','Oct','Nov','Dec'))
2. Inheriting an enum: @unique
adorners can help us check that there are no duplicate values.
1 from Import Enum, Unique 2 3 @unique 4 class Weekday (Enum): 5 # Sun's value is set to 0 6 Mon = 1 7 Tue = 2 8 Wed = 3 9 Thu = 4 Fri = 511 Sat = 6
Python: Notes (3)-Object-oriented programming