classes and objects
1. Classes and Objects and Concepts
- Class: the abstraction of common things, is a description of a class with common things, is a collection with the same attributes and methods
- Object: An instance of a class, an embodiment of a common thing, each individual in this type of thing
2. Summary:
A class is a template for an object, and an object is an instance of a class
3. Syntax for creating a class
class Math: #Class names are usually capitalized a = 4 #Attributes b = 5 def add(self): c = self.a + self.b return c
Notice:
- Class names are generally capitalized, such as class User, where class is a keyword
- A class contains properties (variables) and methods (functions)
- The class function comes with the self keyword, no less! Self points to the object itself, which is a reference to an instance of the class
- If you want to call property (self. property name), method (self. method name) in a class or function
instantiate
1. Instance name = class name(), such as the Math class instantiation above; math_1 = Math()
2. Example
class Friend: def __init__(self, height, age, money): self.height = height self.age = age self.money = money def can_Cook(self, can = True): if can == True: return " Can cook! " else : return " Ca n't cook! " Peter = Friend( " 178 " , 27, " 2000000 " ) print ( " Peter is {0} years old, is {1}cm tall, has a deposit of {2} yuan, and {3} " .format(Peter.age, Peter. height, Peter.money, Peter.can_Cook()))
operation result:
Peter is 27 years old, 178cm tall, has a deposit of 2,000,000, and can cook!