1. Overview
1. Definition class (class Dog(object)) --> Instantiation (d = Dog()) ---> Instance object ( d)
2. __init__() constructor
3. self.name = name class attributes and member variables
4. def say_hi() class method, Dynamic attributes
2. Accessing the attributes of the class
class Role(object): def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money def shot(self): print("%s is shooting..." % self.name) def got_shot(self): print("ah...,%s got shot..." % self.name) def buy_gun(self, gun_name): print("%s just bought %s" % (self.name,gun_name)) r1 = Role('Alex', 'police', 'AK47') # 生成一个角色 r2 = Role('Jack', 'terrorist', 'B22') # 生成一个角色
2.1 Accessing the attributes and methods of the class
We use the instance object.properties/methods to access
r1.shot() # 调用shot 方法 r2.buy_gun('B13') # 调用 buy_gun的方法并传参 print(r1.role) # 打印类的属性 # 输出 Alex is shooting... Jack just bought B13 police
2.1 Modify the properties of the object
In the above example, we changed the weapon for the character r2, namely B22 --> B13. But in fact, when we call the weapon attributes of the character r2, we will find that his weapon has not changed:
r2.buy_gun('B13') print(r2.weapon) # 输出 Jack just bought B13 B22 # 可以发现武器依然是 B22
In fact, we can directly change the attributes of the object when purchasing the weapon:
def buy_gun(self, gun_name): print("%s just bought %s" % (self.name, gun_name)) self.weapon = gun_name # 在方法内改变属性 r2.buy_gun('B13') print(r2.weapon) #输出 Jack just bought B13 B13 # 可以发现武器已经改变
3. Private attributes
3.1. Define private attributes
Class Once an attribute is defined as a private attribute, it cannot be called externally or modified at will. Private properties can only be used within the class.
class Person(object): def __init__(self, name, job, phone, address): self.name = name self.job = job self.phone = phone self.__address = address # 定义一个私有属性 def sayhi(self): print("hell,%s" % self.name) p1 = Person('Bigberg', 'Doctor', '8833421', 'hz') print(p1.name) print(p1.__address) # 访问私有属性 # 输出 Bigberg File "G:/python/untitled/study6/类的私有属性.py", line 17, in <module> print(p1.__address) AttributeError: 'Person' object has no attribute '__address'
The result of the operation is that access to the attribute name is passable, but an error is reported when directly accessing the private attribute self.__address. But if you use other methods, you can still access it.
3.2. The get method accesses private properties
Private properties cannot be accessed directly from the outside, but they can be accessed inside the class, so we can Define a method to get private properties.
class Person(object): def __init__(self, name, job, phone, address): self.name = name self.job = job self.phone = phone self.__address = address def get_private(self): return self.__address def sayhi(self): print("hell,%s" % self.name) p1 = Person('Bigberg', 'Doctor', '8833421', 'hz') res = p1.get_private() print(res) # 输出 hz
3.3 Forced access to private properties
We can also force access to private properties through a method, even Modify the value of a private property. Method: object name._class name__attribute name.
class Person(object): def __init__(self, name, job, phone, address): self.name = name self.job = job self.phone = phone self.__address = address def get_private(self): return self.__address def sayhi(self): print("hell,%s" % self.name) p1 = Person('Bigberg', 'Doctor', '8833421', 'hz') print(p1._Person__address) # 访问私有属性 print("----change----") p1._Person__address = 'BJ' # 修改私有属性 print(p1._Person__address) #输出 hz ----change---- BJ
Classes are an important tool for simplifying and optimizing applications.
1. Inheritance: The ability of subclasses to inherit the characteristics of parent classes. It embodies and expands the sharing of object-oriented programming methods, allowing objects of the same type to share data and program code, improving program reusability. The parent class is a class that can be further defined to derive new classes, and the subclass is a new class established by using other classes as a starting point and defining more specific characteristics.
2. Polymorphism: Some related classes contain methods with the same name, but the content of the methods can be different. Which one to call is determined at runtime based on the class of the object. The same message can lead to different actions when received by different objects.
3. Abstraction: Extract the distinctive features of a class or object without processing other information about the class or object.
4. Summary
1. Define private attributes: self.__private_attr_name = private_attr_name
2. Mandatory Access private attributes: object name._class name__attribute name (d._dog__sex)
3. Provide external read-only interface access:
Def get_sex(self):
return self.__sex
The above is the detailed content of Introduction to classes and attributes. For more information, please follow other related articles on the PHP Chinese website!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft