Home  >  Article  >  Backend Development  >  Introduction to classes and attributes

Introduction to classes and attributes

巴扎黑
巴扎黑Original
2017-07-21 14:14:241366browse

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

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

 

 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

 

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:
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