Introduction to classes and attributes
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Everyone knows that there are many versions of win7 system, such as win7 ultimate version, win7 professional version, win7 home version, etc. Many users are entangled between the home version and the ultimate version, and don’t know which version to choose, so today I will Let me tell you about the differences between Win7 Family Meal and Win7 Ultimate. Let’s take a look. 1. Experience Different Home Basic Edition makes your daily operations faster and simpler, and allows you to access your most frequently used programs and documents faster and more conveniently. Home Premium gives you the best entertainment experience, making it easy to enjoy and share your favorite TV shows, photos, videos, and music. The Ultimate Edition integrates all the functions of each edition and has all the entertainment functions and professional features of Windows 7 Home Premium.

Understand the key features of SpringMVC: To master these important concepts, specific code examples are required. SpringMVC is a Java-based web application development framework that helps developers build flexible and scalable structures through the Model-View-Controller (MVC) architectural pattern. web application. Understanding and mastering the key features of SpringMVC will enable us to develop and manage our web applications more efficiently. This article will introduce some important concepts of SpringMVC

With the rapid development of the Internet, programming languages are constantly evolving and updating. Among them, Go language, as an open source programming language, has attracted much attention in recent years. The Go language is designed to be simple, efficient, safe, and easy to develop and deploy. It has the characteristics of high concurrency, fast compilation and memory safety, making it widely used in fields such as web development, cloud computing and big data. However, there are currently different versions of the Go language available. When choosing a suitable Go language version, we need to consider both requirements and features. head

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

The three characteristics of 5g are: 1. High speed; in practical applications, the speed of 5G network is more than 10 times that of 4G network. 2. Low latency; the latency of 5G network is about tens of milliseconds, which is faster than human reaction speed. 3. Broad connection; the emergence of 5G network, combined with other technologies, will create a new scene of the Internet of Everything.

C++ functions have the following types: simple functions, const functions, static functions, and virtual functions; features include: inline functions, default parameters, reference returns, and overloaded functions. For example, the calculateArea function uses π to calculate the area of a circle of a given radius and returns it as output.

The characteristics of Java are: 1. Simple and easy to learn; 2. Object-oriented, making the code more reusable and maintainable; 3. Platform-independent, able to run on different operating systems; 4. Memory management, through automatic garbage collection mechanism Manage memory; 5. Strong type checking, variables must declare their type before use; 6. Security, which can prevent unauthorized access and execution of malicious code; 7. Multi-threading support, which can improve the performance and responsiveness of the program ; 8. Exception handling can avoid program crashes; 9. A large number of development libraries and frameworks; 10. Open source ecosystem.

LinuxGem is a common term in the computer field, which refers to software or applications that perform well on the Linux operating system. The Linux operating system itself is an open source operating system with the support of many developers and communities, so it is easy to find high-quality, powerful software on Linux. However, even among so many high-quality software, there are still some software called "LinuxGem", which are popular in Linux with their excellent design, performance and functions.
