Hướng dẫn how to increment class variable in python - cách tăng biến lớp trong python

Tôi có một lớp đơn giản và mỗi lần tôi tạo một thể hiện của lớp đó, tôi muốn biến lớp tăng lên như thế nào tôi nên làm điều đó với mã này:

class Person:

    person_count = 0

    def __init__[self, username]:
        self.username = username

ashley = Person["Ash"]
daphne = Person["Daph"]

Person.person_count #I want this to be 2

Đã hỏi ngày 12 tháng 2 năm 2017 lúc 20:54Feb 12, 2017 at 20:54

teddybear123teddybear123teddybear123

2.1645 huy hiệu vàng23 Huy hiệu bạc38 Huy hiệu đồng5 gold badges23 silver badges38 bronze badges

Chỉ cần tăng biến lớp trong __init__:

class Person[object]:

    person_count = 0

    def __init__[self, username]:
        self.username = username
        Person.person_count += 1  # here

ashley = Person["Ash"]
daphne = Person["Daph"]

print[Person.person_count]
# 2

Và đừng quên phân lớp từ

class Person[object]:

    person_count = 0

    def __init__[self, username]:
        self.username = username
        Person.person_count += 1  # here

ashley = Person["Ash"]
daphne = Person["Daph"]

print[Person.person_count]
# 2
0 nếu bạn đang ở trên Python 2.

Xem mục đích của lớp con "đối tượng" trong Python là gì?

Đã trả lời ngày 12 tháng 2 năm 2017 lúc 20:55Feb 12, 2017 at 20:55

Moses Koledoyemoses KoledoyeMoses Koledoye

76K8 Huy hiệu vàng125 Huy hiệu bạc133 Huy hiệu đồng8 gold badges125 silver badges133 bronze badges

0

Bạn sẽ phải tăng biến của lớp trong __init__ như:

class Person:
    person_count = 0
    def __init__[self, username]:
        self.username = username
        self.__class__.person_count += 1
        # OR, 
        # Person.person_count += 1

Example:

>>> ashley = Person["Ash"]
>>> ashley.person_count
1
>>> daphne = Person["Daph"]
>>> daphne.person_count
2

Bạn cũng có thể trích xuất số lượng trực tiếp bằng cách sử dụng lớp như:

>>> Person.person_count
2

Đã trả lời ngày 12 tháng 2 năm 2017 lúc 20:56Feb 12, 2017 at 20:56

Moinuddin Quadrimoinuddin QuadriMoinuddin Quadri

45K12 Huy hiệu vàng93 Huy hiệu bạc121 Huy hiệu đồng12 gold badges93 silver badges121 bronze badges

Sử dụng phương thức __init__ để tăng biến lớp của bạn:

class Person:
    person_count = 0
    def __init__[self, username]:
        self.username = username
        Person.person_count += 1

Một biến lớp có thể được truy cập bằng cách sử dụng tên của lớp, vì vậy trong trường hợp này là

class Person[object]:

    person_count = 0

    def __init__[self, username]:
        self.username = username
        Person.person_count += 1  # here

ashley = Person["Ash"]
daphne = Person["Daph"]

print[Person.person_count]
# 2
3. Hãy nhớ rằng bạn cũng có thể truy cập biến lớp này từ trường hợp, vì vậy:

>>> p1 = Person['person1']
>>> Person.person_count
1
>> p1.person_count
1
>> p2 = Person['person2']
>>> Person.person_count
2
>> p1.person_count
2
>> p2.person_count
2

Đã trả lời ngày 12 tháng 2 năm 2017 lúc 21:01Feb 12, 2017 at 21:01

lmiguelvargasflmiguelvargasflmiguelvargasf

57.1K43 Huy hiệu vàng212 Huy hiệu bạc215 Huy hiệu Đồng43 gold badges212 silver badges215 bronze badges

Tôi đã thực hiện một thử thách mã cho Codecademy và đây là giải pháp cố gắng của tôi:

        class DriveBot:
  # Create a counter to keep track of how many robots were created
        robot_count = 0
        all_disabled = False
        latitude = -999999
        longitude = -999999

        def __init__[self, motor_speed = 0, direction = 180, sensor_range = 10, id = robot_count + 1]:
            self.motor_speed = motor_speed
            self.direction = direction
            self.sensor_range = sensor_range
            self.id = id
            DriveBot.robot_count += 1
        # Assign an `id` to the robot when it is constructed by incrementing the counter and assigning the value to `id`
    
        def control_bot[self, new_speed, new_direction]:
            self.motor_speed = new_speed
            self.direction = new_direction
    
        def adjust_sensor[self, new_sensor_range]:
            self.sensor_range = new_sensor_range

        robot_1 = DriveBot[]
        robot_1.motor_speed = 5
        robot_1.direction = 90
        robot_1.sensor_range = 10

        robot_2 = DriveBot[35, 75, 25]
        robot_3 = DriveBot[20, 60, 10]

        print[robot_1.id]
        print[robot_2.id]
        print[robot_3.id]

Mục tiêu là cung cấp cho mỗi đối tượng robot một ID tăng lên. Robot đầu tiên là ID 1, robot thứ hai là ID 2, v.v. Mã của tôi cung cấp cho mỗi robot một ID là 1. Không tốt.

Đây là mã giải pháp:

        class DriveBot:
        all_disabled = False
        latitude = -999999
        longitude = -999999
        robot_count = 0

        def __init__[self, motor_speed = 0, direction = 180, sensor_range = 10]:
            self.motor_speed = motor_speed
            self.direction = direction
            self.sensor_range = sensor_range
            DriveBot.robot_count += 1
            self.id = DriveBot.robot_count
    
        def control_bot[self, new_speed, new_direction]:
            self.motor_speed = new_speed
            self.direction = new_direction

        def adjust_sensor[self, new_sensor_range]:
            self.sensor_range = new_sensor_range

    robot_1 = DriveBot[]
    robot_1.motor_speed = 5
    robot_1.direction = 90
    robot_1.sensor_range = 10

    robot_2 = DriveBot[35, 75, 25]
    robot_3 = DriveBot[20, 60, 10]

    print[robot_1.id]
    print[robot_2.id]
    print[robot_3.id]

Tôi nhận thấy rằng giải pháp không xác định ID trong các tham số lớp. Cái này hoạt động ra sao? Tại sao tôi không thể tăng một biến lớp bằng tham số lớp, thay vì sử dụng biến thể hiện?

Bạn có thể tăng một biến trong Python không?

Nếu bạn quen thuộc với Python, bạn sẽ biết các toán tử tăng và giảm [cả trước và sau] không được phép trong đó. Python được thiết kế để nhất quán và có thể đọc được.Increment and Decrement operators [ both pre and post] are not allowed in it. Python is designed to be consistent and readable.

Python có ++ không

Python, theo thiết kế, không cho phép sử dụng toán tử ++.Thuật ngữ ++, được gọi là toán tử tăng trong C ++ / Java, không có vị trí trong Python.does not allow the use of the ++ “operator”. The ++ term, is called the increment operator in C++ / Java, does not have a place in Python.

Chúng ta có thể sửa đổi các biến lớp Python không?

Sửa đổi các biến lớp Tuy nhiên, chúng tôi có thể thay đổi giá trị của biến lớp trong lớp hoặc bên ngoài lớp.Lưu ý: Chúng ta nên thay đổi giá trị của biến lớp chỉ bằng tên lớp.Lưu ý: Đó là cách thực hành tốt nhất để sử dụng tên lớp để thay đổi giá trị của biến lớp.we can change the value of the class variable either in the class or outside of class. Note: We should change the class variable's value using the class name only. Note: It is best practice to use a class name to change the value of a class variable.

Làm thế nào là sự gia tăng biến trong Python bằng 1?

Chúng ta hãy xem một ví dụ đơn giản để tăng một biến với 1. Chúng ta đã sử dụng một biến có giá trị 0 lúc đầu.Giá trị ban đầu đã được in ra, và sau đó giá trị đã được tăng lên bởi 1 bằng cách sử dụng dấu hiệu+= =.Sau đó, giá trị mới phải là 1 bây giờ.using the “+=” sign. Then the new value should be 1 now.

Bài Viết Liên Quan

Chủ Đề