Table of Contents
1. Overview" >1. Overview
2. Accessing the attributes of the class" >2. Accessing the attributes of the class
 2.1 Accessing the attributes and methods of the class" > 2.1 Accessing the attributes and methods of the class
 2.1 Modify the properties of the object" > 2.1 Modify the properties of the object
3. Private attributes" >3. Private attributes
3.1. Define private attributes" > 3.1. Define private attributes
3.2. The get method accesses private properties" > 3.2. The get method accesses private properties
3.3 Forced access to private properties" > 3.3 Forced access to private properties
4. Summary" >4. Summary
Home Backend Development Python Tutorial Introduction to classes and attributes

Introduction to classes and attributes

Jul 21, 2017 pm 02:14 PM
characteristic

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')   # 生成一个角色
Copy after login

 

 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
Copy after login

 

 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
Copy after login

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    # 可以发现武器已经改变
Copy after login

 

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: &#39;Person&#39; object has no attribute &#39;__address&#39;
Copy after login

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(&#39;Bigberg&#39;, &#39;Doctor&#39;, &#39;8833421&#39;, &#39;hz&#39;)
res = p1.get_private()
print(res)

# 输出
hz
Copy after login

 

 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(&#39;Bigberg&#39;, &#39;Doctor&#39;, &#39;8833421&#39;, &#39;hz&#39;)

print(p1._Person__address)   # 访问私有属性

print("----change----")
p1._Person__address = &#39;BJ&#39;    # 修改私有属性
print(p1._Person__address)

#输出
hz
----change----
BJ
Copy after login

 

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Introduction to the differences between win7 home version and win7 ultimate version Introduction to the differences between win7 home version and win7 ultimate version Jul 12, 2023 pm 08:41 PM

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.

Master the key concepts of Spring MVC: Understand these important features Master the key concepts of Spring MVC: Understand these important features Dec 29, 2023 am 09:14 AM

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

Choose the applicable Go version, based on needs and features Choose the applicable Go version, based on needs and features Jan 20, 2024 am 09:28 AM

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

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

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

What are the three characteristics of 5g What are the three characteristics of 5g Dec 09, 2020 am 10:55 AM

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++ function types and characteristics C++ function types and characteristics Apr 11, 2024 pm 03:30 PM

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.

What are the characteristics of java What are the characteristics of java Aug 09, 2023 pm 03:05 PM

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.

What are Linux gems? Learn more about the definition and characteristics of Linux Gem What are Linux gems? Learn more about the definition and characteristics of Linux Gem Mar 14, 2024 pm 02:18 PM

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.

See all articles