Attributes are used to describe some characteristics of a class , Such as color , brand , Models belong to mobile phone properties .
Methods are used to express some functions of this class , Such as taking photos , Calling is the way of mobile phone .
Use keywords class Create a class , Here is a case :
class Phone():
def call(self,who):
return f" Calling {who}"
def sendmessage(self,who,txt):
return f" Sending text message to {who}, The content is {txt}"
self Parameters , Parameters automatically passed in by the program , Refers to the object that calls the method . The first parameter is zero self, Is a fixed way to define instance methods .
Objects are created with classes as templates .
Here we use Phone Class to instantiate two objects to represent your mobile phone and my mobile phone .
class Phone():
def call(self,who):
return f" Calling {who}"
def sendmessage(self,who,txt):
return f" Sending text message to {who}, The content is {txt}"
myphone=Phone() //myphone Variable name , The name set for the object
yourphone=Phone() // Parentheses mean calling you Phone Instantiate an object
ret=myphone.call("Tony") //Tony It belongs to the argument
print(ret)
ret2=yourphone.sendmessage("Jenney"," Noon to eat anything ?")
print(ret2)
init There are two underscores on the left and right , That is, the whole name has four underscores .
Initialization here is similar to factory settings , Express “ Be prepared at the beginning .” It will be called automatically when the object is created .
class Phone():
def __init__(self,bd,clr):
print(" When creating an instance object , Call this method automatically ")
self.brand=bd // Because there is no object created here , All object names use self Parameters instead of
self.color=clr
myphone=Phone(" Huawei "," white ")
yourphone=Phone(" Apple "," black ")
print(f" I have one {myphone.color} Of {myphone.brand} mobile phone ")
print(f" You have one {yourphone.color} Of {yourphone.brand} mobile phone ")
Through the previous examples , We can know , The attribute and method of an object need to connect the object name and method name with a period representation . But when defining classes , Because we don't know which objects to define , therefore self The function of is to instantiate the object name ( quote ) Pass it on to the method . For example myphone In the object ,self.brand It stands for myphone.brand
In fact, the string we usually create 、 list 、 Tuples are essentially objects of this type . So it's called directly print()、range() function , Expressed by a period append()、keys() Wait for a method of an object .