程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Summary analysis of Python learning, methods, attributes and inheritance (detailed)

編輯:Python

Catalog

One 、 class

Create a class :

Two 、 Method :

(1) Create method :

(2) Calling method :

① Call... Through an instance object :

② Call directly through the class ( You need to pass an instance object ):

③ While the program instantiates the object , Automatically called .

3、 ... and 、 attribute :

1、 Instance attributes :

2、 Class properties ( Class variables ):

Four 、 Class inheritance :

1、 Rule of grammar :

 2、 Overriding methods in inheritance :

3、 Calls a method of the parent class __init__( ):


One 、 class

Create a class :

Rule of grammar :class Class name (object):

pass

class: keyword Class name : Hump ( Capitalize the first letter of each word ) object: Default inheritance

Class cannot be used directly , You need to convert it into an instance , To use , The process of generating instance objects through classes is called instantiation .

  Methods for creating instance objects : Class name ()

class Person(object):
pass
class Animal(object):
pass
andy = Person()
jack = Person()
dog = Animal()
cat = Animal()

Two 、 Method :

Methods generally represent the behavior of this object , It is usually the behavior of the object . Divided into methods __init__( ) And the common way .

(1) Create method :

Grammatical structure :def Method name (self,args):

                pass

def: keyword Method name : All lowercase characters are required self: Instance object args: Parameters

Method names are all lowercase “_” Division , for example :get_student_name;get_goods_order

(2) Calling method :

① Call... Through an instance object :

class Animal(object):
def eat(self,food):
print(f" Is eating {food}")
def play(self):
print(" Playing ")
def sleep(self):
print(" be sleeping ")
dog = Animal()
dog.eat(" Dog food ")
dog.play()
dog.sleep()

Running results :

  In the process of calling class methods through instance objects , You do not need to fill in... When passing parameters self, because self Is an instance object , By default , The first parameter is self, The program defaults to self Make an assignment . So we only need to add the second parameter when calling args. But the instance object can only call the methods already defined in the class , If there is no definition, it cannot be called .

② Call directly through the class ( You need to pass an instance object ):

class Animal(object):
def eat(self, food):
print(f" Is eating {food}")
def play(self):
print(" Playing ")
def sleep(self):
print(" be sleeping ")
dog = Animal()
Animal.eat(dog," Dog food ")
Animal.play(dog)
Animal.sleep(dog)

Running results :

 

In the process of calling class methods directly through classes , When passing parameters, you must pass an instance object (self), Of course there are parameters args You still need to add parameters . This method is more troublesome , Therefore, we usually call class methods through instance objects .

Other functions of the instance object : When our instantiation is complete , Of each method in the class self It's all the same , So you can cross use . When we learn function nesting , We learned that you can call other functions in one function , Similarly, the same is true for class methods , Instance object self You can use each other in each method , Because every method has self, And the mutual calls between methods , It is the same as nested calls between functions . because self Is an instance object of a class , Once the class is instantiated , All instance objects are self.

class Animal(object):
def eat(self, food):
print(f" Is eating {food}")
def play(self):
print(" Playing ")
def sleep(self):
self.eat(" Dog food ") # dog.eat(" Dog food ")
print(" be sleeping ")
dog = Animal()
dog.sleep() # Animal.sleep(dog)

Running results :

 

③ While the program instantiates the object , Automatically called .

It's a special method :__init__ Initialization method . In the name of the method , There are two underscores at the beginning and the end , It's a convention , To avoid python The default method has a name conflict with the normal method . Make sure that __init__( ) There are two underscores on both sides of the , Otherwise, when you use classes to create instances , This method will not be called automatically , Which leads to hard to find errors .

So how to initialize ? When defining this method , Define some parameters that need to be initialized , Shape parameter self essential , And must precede other formal parameters , Other formal parameters can be omitted , It can be multiple . There is no need to pass... When passing parameters self, Because every method call associated with an instance automatically passes arguments self, It is a reference to the instance itself , Gives instances access to properties and methods in the class , But if there are other formal parameters , We need to pass the corresponding arguments . What's more, we need to pay attention to , because __init__( ) Will run first , So we usually write this method at the beginning of all methods .

class Animal(object):
def __init__(self,name,age):
self.name = name
self.age = age
print(" I'm an animal ")
def eat(self, food):
print(f" Is eating {food}")
def play(self):
print(f"{self.name} This year, {self.age} year , Playing ")
def sleep(self):
print(" be sleeping ")
dog = Animal(" Poodle ",10)
dog.play()
pig = Animal(" Peppa Pig ",8)
pig.play()

  Running results :

3、 ... and 、 attribute :

Variables that can be accessed through an instance are attributes . It is divided into Instance attributes and Class properties .

1、 Instance attributes :

Format : example . attribute

class Animal(object):
def __init__(self,name,age):
self.name = name
self.age = age
print(" I'm an animal ")
def eat(self, food):
print(f" Is eating {food}")
def play(self):
print(f"{self.name} This year, {self.age} year , Playing ")
def sleep(self):
print(" be sleeping ")
dog = Animal(" Poodle ",10)
dog.play()
dog.gender = " male "
print(dog.gender)

Running results :

 

In this code self.name and self.gender in ,name and gender Instance properties . Instance properties can be defined internally , Usually in __init__ Initialization method , You can also dynamically define , That is, externally defined . When calling instance properties , We can go through self. Call... In this form .

class Animal(object):
age = 5
def eat(self,food):
print(f" Is eating {food}")
def play(self):
print(" Playing ")
def sleep(self):
print(" be sleeping ")
dog = Animal()
pig = Animal()
print(dog.age)
print(pig.age)
print(Animal.age)

2、 Class properties ( Class variables ):

The methods defined are similar to variables . The defined location is inside the class , Outside other functions . Class attributes are common to every instance object , That is, the instance object can share the properties of the class . Calling class properties can be called through an instance object , You can also directly call... Through classes .

When we create a class , Create a class attribute and assign a value . Instantiate the class as two instance objects . Then both instance objects will have a property value , The value is the value of the class attribute .

class Animal(object):
age = 5
def eat(self,food):
print(f" Is eating {food}")
def play(self):
print(" Playing ")
def sleep(self):
print(" be sleeping ")
dog = Animal()
pig = Animal()
print(dog.age)
print(pig.age)
print(Animal.age)

Running results :

 

however , When we dynamically generate an attribute from one of the objects , And the assignment , Then this object will not inherit the value of the class attribute , However, the value of another unchanged object's attribute is still the value of the class attribute .

class Animal(object):
age = 5
def eat(self,food):
print(f" Is eating {food}")
def play(self):
print(" Playing ")
def sleep(self):
print(" be sleeping ")
Animal.age = 8
dog = Animal()
dog.age = 10
pig = Animal()
print(f"dog Of age yes {dog.age}")
print(f"pig Of age yes {pig.age}")
print(f"Animal Of age yes {Animal.age}")

Running results :

 

  summary : The attribute value of the instance object takes precedence over its own , If itself is not assigned , Then take the value of the class attribute .

Four 、 Class inheritance :

1、 Rule of grammar :

Write a class , You don't always have to start with a blank . If you write a class that is a special version of another existing class , You can use Inherit . One class Inherit Another class time , Will automatically get all the properties and methods of another class . The original class becomes Parent class , The new class becomes Subclass . The subclass inherits all the properties and methods of the parent class , You can also define your own properties and methods . When you create a subclass , The parent class must be contained in the current folder , And before the subclass .

The syntax rule of class is :class Class name (object):

                          pass

If you want to use inheritance for this class , Will object Change to the name of a parent class :

 

class Animal(object):
age = 5
def __init__(self,name):
self.name = name
def eat(self):
print(f"{self.name} Eating ")
def play(self):
print(f"{self.name} Playing ")
def sleep(self):
print(f"{self.name} be sleeping ")
class Dog(Animal):
def bark(self):
print(f"{self.name} Will bark ")
class Pig(Animal):
def buu(self):
print(f" The little pig will be called ")
dog = Dog(" Sausage dog ") # When we instantiate subclasses , The initialization method of the parent class will be called automatically , So pass the parameters name
dog.eat()
dog.bark()
print(dog.age)

Running results : 

 

 2、 Overriding methods in inheritance :

When the subclass contains the same method as the parent class , Subclasses will call their own methods first , If its own method does not exist , To call the methods of the parent class .( Subclasses override methods of the parent class )

class Animal(object):
age = 5
def __init__(self,name):
self.name = name
def eat(self):
print(f"{self.name} Eating ")
def play(self):
print(f"{self.name} Playing ")
def sleep(self):
print(f"{self.name} be sleeping ")
class Dog(Animal):
def eat(self):
print(f"{self.name} Eating dog food ")
def bark(self):
print(f"{self.name} Will bark ")
class Pig(Animal):
def eat(self):
print(f"{self.name} Eating pig food ")
def buu(self):
print(f" The little pig will be called ")
dog = Dog(" Sausage dog ")
dog.eat()
pig = Pig(" Domestic pig ")
pig.eat()

  Running results :

3、 Calls a method of the parent class __init__( ):

When both the subclass and the parent class contain methods __init__( ) when , The initialization method of the child class will override the initialization method of the parent class . But when we write new classes based on existing classes , You usually call the method of the parent class __init__( ), At this time, if we want to keep the initialization method of the parent class , Need to use super() function ,super With the meaning of superior , This function means to call the superior of the subclass , That is, the parent class . The format is super( ).__init__(args). If the initialization method of the parent class contains parameters , The initialization method of the subclass should also contain the corresponding parameters , And then through args receive .

class Animal(object):
def __init__(self,name):
self.name = name
def eat(self):
print(f"{self.name} Eating ")
def play(self):
print(f"{self.name} Playing ")
def sleep(self):
print(f"{self.name} be sleeping ")
class Dog(Animal):
def __init__(self,name,age):
super().__init__(name)
self.age = age
def eat(self):
print(f"{self.name} This year, {self.age} Year old , Eating dog food ")
def bark(self):
print(f"{self.name} Will bark ")
dog = Dog(" Sausage dog ",10)
dog.eat()

Running results :

 

  It's not easy to create ! If you think it's OK, you can like it , thank you !

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved