Tôi có một lớp học với một từ điển.
Tôi tạo n trường hợp số của lớp.
Khi i += các giá trị trên một khóa trong từ điển đó, nó được phản ánh trong mỗi đối tượng tôi đã khởi tạo từ đối tượng đó.
Làm cách nào để làm cho từ điển đó trở nên độc đáo cho mọi khởi tạo của lớp đó?
Đây là cách tôi tạo đối tượng:
for num in range[0, numOfPlayers]:
listOfPlayerFleets.append[fleet.Fleet[]]
Dưới đây là cách gọi phương thức bổ sung. Tôi có điều này trong một vòng lặp và đã xác minh rằng Int Int Int đang tăng lên mỗi lần.
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
Đây là mã trong đối tượng đội tàu của tôi dưới đây cho ví dụ.
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
Trong pydev khi tôi bước qua chức năng này, hãy gọi mọi đối tượng với ShipNamesAndNumbers được tăng lên bởi NumboAdd.
Điều này xảy ra ngay cả những đối tượng đội tàu ở các vị trí khác nhau trong bộ nhớ.
Tôi có phải truyền từ điển từ một lớp khác không? Tôi đã viết một lớp kiểm tra chỉ để xác minh điều này:
class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
Lớp FOO không có vấn đề tương tự như các đối tượng đội tàu của tôi có tất cả các từ điển của chúng được sửa đổi khi một từ điển được sửa đổi.
Vì vậy, điều này đã làm cho tôi thậm chí còn bối rối hơn.
Làm thế nào để bạn gọi một biến lớp trong Python?
Các biến được xác định bên trong lớp nhưng bên ngoài phương thức có thể được truy cập trong lớp [tất cả các phương thức bao gồm] bằng cách sử dụng thể hiện của một lớp. Ví dụ - bản thân. var_name. Nếu bạn muốn sử dụng biến đó ngay cả bên ngoài lớp, bạn phải khai báo biến đó là toàn cầu.
- Làm cách nào để đặt một biến thể hiện trong Python?: If the value of a variable varies from object to object, then such variables are called instance variables.
- Chúng ta có thể truy cập biến thể hiện bằng toán tử đối tượng và dấu chấm [.]. Trong Python, để làm việc với một biến thể hiện và phương thức, chúng tôi sử dụng từ khóa tự. Chúng tôi sử dụng từ khóa tự làm tham số đầu tiên cho một phương thức.: A class variable is a variable that is declared inside of class, but outside of any instance method or
3 method.class Fleet: """ Stores Fleet Numbers, Represents a fleet """ shipNamesandNumber = {} def addShip[self, type, numToAdd]: self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
Trong lập trình hướng đối tượng, khi chúng tôi thiết kế một lớp, chúng tôi sử dụng các biến thể hiện và biến lớp.:
- Trong lớp, các thuộc tính có thể được xác định thành hai phần:
- Các biến thể hiện: Nếu giá trị của một biến thay đổi từ đối tượng này sang đối tượng khác, thì các biến đó được gọi là biến thể hiện.
- Các biến lớp: Một biến lớp là một biến được khai báo bên trong lớp, nhưng ngoài bất kỳ phương thức thể hiện nào hoặc & nbsp; ________ 23 & nbsp; phương thức.
- Sau khi đọc bài viết này, bạn sẽ học:
Cách tạo và truy cập các biến lớp
Sửa đổi các giá trị của một biến lớpvalue of a variable is not varied from object to object, such types of variables are called class variables or static variables.
Biến trường hợp so với các biến lớpshared by all instances of a class. Unlike instance variable, the value of a class variable is not varied from object to object,
Hành vi của một biến lớp trong kế thừa
Một biến lớp trong Python là gì?
Nếu giá trị của một biến không thay đổi từ đối tượng sang đối tượng, các loại biến đó được gọi là biến lớp hoặc biến tĩnh.
Chúng tôi có thể thêm bất kỳ số lượng biến lớp trong một lớp.
Tạo các biến lớp
Một biến lớp được khai báo bên trong lớp, nhưng ngoài bất kỳ phương thức thể hiện nào hoặc & nbsp; ________ 23 & nbsp; phương thức.
Theo quy ước, thông thường nó được đặt ngay bên dưới tiêu đề lớp và trước phương thức cấu trúc và các phương thức khác.
Example::
class Student:
# Class variable
school_name = 'ABC School '
def __init__[self, name, roll_no]:
self.name = name
self.roll_no = roll_no
# create first object
s1 = Student['Emma', 10]
print[s1.name, s1.roll_no, Student.school_name]
# access class variable
# create second object
s2 = Student['Jessa', 20]
# access class variable
print[s2.name, s2.roll_no, Student.school_name]
Đầu ra
Emma 10 ABC School Jessa 20 ABC School
Trong ví dụ trên, chúng tôi đã tạo biến lớp
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
5 và truy cập nó bằng tên đối tượng và tên lớp.Lưu ý: Giống như các biến thông thường, các biến lớp có thể lưu trữ dữ liệu thuộc bất kỳ loại nào. Chúng ta có thể sử dụng danh sách Python, Tuple Python và Dictiony Python như một biến lớp.: Like regular variables, class variables can store data of any type. We can use Python list, Python tuple, and Python dictionary as a class variable.
Truy cập các biến lớp
Chúng ta có thể truy cập các biến tĩnh bằng tên lớp hoặc theo tham chiếu đối tượng, nhưng nên sử dụng tên lớp.
Trong Python, chúng ta có thể truy cập biến lớp ở những nơi sau
- Truy cập bên trong hàm tạo bằng cách sử dụng tham số
6 hoặc tên lớp.class Fleet: """ Stores Fleet Numbers, Represents a fleet """ shipNamesandNumber = {} def addShip[self, type, numToAdd]: self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
- Truy cập biến lớp bên trong Phương thức thể hiện bằng cách sử dụng tên của lớp
- Truy cập từ bên ngoài lớp bằng cách sử dụng tham chiếu đối tượng hoặc tên lớp.
Ví dụ 1: Biến lớp truy cập trong hàm tạo: Access Class Variable in the constructor
class Student:
# Class variable
school_name = 'ABC School '
# constructor
def __init__[self, name]:
self.name = name
# access class variable inside constructor using self
print[self.school_name]
# access using class name
print[Student.school_name]
# create Object
s1 = Student['Emma']
Đầu ra
ABC School ABC School
Trong ví dụ trên, chúng tôi đã tạo biến lớp
5 và truy cập nó bằng tên đối tượng và tên lớp.: Access Class Variable in Instance
method and outside classclass Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
class Student:
# Class variable
school_name = 'ABC School '
# constructor
def __init__[self, name, roll_no]:
self.name = name
self.roll_no = roll_no
# Instance method
def show[self]:
print['Inside instance method']
# access using self
print[self.name, self.roll_no, self.school_name]
# access using class name
print[Student.school_name]
# create Object
s1 = Student['Emma', 10]
s1.show[]
print['Outside class']
# access class variable outside class
# access using object reference
print[s1.school_name]
# access using class name
print[Student.school_name]
Đầu ra
Inside instance method Emma 10 ABC School ABC School Outside class ABC School ABC School
Trong ví dụ trên, chúng tôi đã tạo biến lớp
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
5 và truy cập nó bằng tên đối tượng và tên lớp.Lưu ý: Giống như các biến thông thường, các biến lớp có thể lưu trữ dữ liệu thuộc bất kỳ loại nào. Chúng ta có thể sử dụng danh sách Python, Tuple Python và Dictiony Python như một biến lớp.
Truy cập các biến lớp
Chúng ta có thể truy cập các biến tĩnh bằng tên lớp hoặc theo tham chiếu đối tượng, nhưng nên sử dụng tên lớp.: We should change the class variable’s value using the class name only.
Trong Python, chúng ta có thể truy cập biến lớp ở những nơi sau
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
0Output::
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
1Note::
Truy cập bên trong hàm tạo bằng cách sử dụng tham số
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
6 hoặc tên lớp.Example::
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
2Output::
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
3Truy cập biến lớp bên trong Phương thức thể hiện bằng cách sử dụng tên của lớp
Truy cập từ bên ngoài lớp bằng cách sử dụng tham chiếu đối tượng hoặc tên lớp.
Ví dụ 1: Biến lớp truy cập trong hàm tạo
Ví dụ 2: Biến lớp truy cập trong phương thức ví dụ và lớp bên ngoài
- Trong ví dụ này, chúng tôi đã truy cập biến lớp
5 bằng tên lớp và từ khóaclass Fleet: """ Stores Fleet Numbers, Represents a fleet """ shipNamesandNumber = {} def addShip[self, type, numToAdd]: self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
6 bên trong một phương thức.: Instance variable’s value varies from object to object. Instance variables are not shared by objects. Every object has its own copy of the instance attributeclass Fleet: """ Stores Fleet Numbers, Represents a fleet """ shipNamesandNumber = {} def addShip[self, type, numToAdd]: self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
- Sửa đổi các biến lớp: A class variable is a variable that is declared inside of class, but outside of any instance method or
3 method. Class variables are shared by all instances of a class.class Fleet: """ Stores Fleet Numbers, Represents a fleet """ shipNamesandNumber = {} def addShip[self, type, numToAdd]: self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
Nói chung, chúng tôi gán giá trị cho một biến lớp bên trong khai báo lớp. Tuy nhiên, chúng ta có thể thay đổi giá trị của biến lớp trong lớp hoặc bên ngoài lớp.: Instance variables in Python with Examples
Đó là thực tiễn tốt nhất để sử dụng tên lớp để thay đổi giá trị của biến lớp. Bởi vì nếu chúng ta cố gắng thay đổi giá trị biến lớp của lớp bằng cách sử dụng một đối tượng, một biến thể hiện mới được tạo cho đối tượng cụ thể đó, trong đó làm mờ các biến lớp. | Một biến thể hiện mới được tạo cho đối tượng S1 và biến này làm mờ các biến lớp. Vì vậy, luôn luôn sử dụng tên lớp để sửa đổi biến lớp. |
Biến lớp so với biến thể hiện | Bảng sau đây cho thấy sự khác biệt giữa biến thể hiện và biến lớp. |
Trong Python, các thuộc tính có thể được xác định thành hai phần: | Các biến thể hiện: Giá trị biến thể thay đổi từ đối tượng này sang đối tượng khác. Các biến thể hiện không được chia sẻ bởi các đối tượng. Mỗi đối tượng đều có bản sao riêng của thuộc tính thể hiện |
Các biến lớp: Một biến lớp là một biến được khai báo bên trong lớp, nhưng ngoài bất kỳ phương thức thể hiện nào hoặc & nbsp; ________ 23 & nbsp; phương thức. Các biến lớp được chia sẻ bởi tất cả các trường hợp của một lớp. | Đọc thêm: Các biến thể hiện trong Python với các ví dụ |
Example::
Biến lớp
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
4Output::
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
5Các biến thể hiện không được chia sẻ bởi các đối tượng. Mỗi đối tượng đều có bản sao riêng của thuộc tính thể hiện
Các biến lớp được chia sẻ bởi tất cả các trường hợp.
Các biến thể hiện được khai báo bên trong hàm tạo, tức là phương thức
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
3.Các biến lớp được khai báo bên trong định nghĩa lớp nhưng ngoài bất kỳ phương thức và hàm tạo thể nào.
Trong Python, chúng ta có thể truy cập biến lớp ở những nơi sau
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
6Đầu ra
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
7Trong ví dụ trên, chúng tôi đã tạo biến lớp
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
5 và truy cập nó bằng tên đối tượng và tên lớp.child
class and parent class has the same class variable name. In this case, the child class will not inherit the class variable of a base class. So it is recommended to create a separate class variable for child class instead of inheriting the base class variable.Example::
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
8Output::
listOfPlayerFleets[currentPlayer].addShip[typeOfShip, num]
9Lưu ý: Giống như các biến thông thường, các biến lớp có thể lưu trữ dữ liệu thuộc bất kỳ loại nào. Chúng ta có thể sử dụng danh sách Python, Tuple Python và Dictiony Python như một biến lớp.
Truy cập các biến lớp
Ví dụ,
Thí dụ
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
0Đầu ra
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
1Trong ví dụ trên, biến thể hiện
class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
1 là duy nhất cho mỗi người chơi. Biến lớp class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
2 và class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
3 có thể được truy cập và sửa đổi bởi bất kỳ đối tượng nào.Bởi vì cả hai đối tượng đã sửa đổi biến lớp, một biến thể hiện mới được tạo cho đối tượng cụ thể đó có cùng tên với biến lớp, tạo ra các biến lớp.
Trong trường hợp của chúng tôi, đối với đối tượng
class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
4 Biến phiên bản mới class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
5 sẽ được tạo và đối tượng class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
6 Biến phiên bản mới class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
3 được tạo.Vì vậy, khi bạn cố gắng truy cập biến lớp bằng đối tượng
class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
4 hoặc class Foo:
"""Testing class with a dictionary"""
myDictionary = {}
def __init__[self]:
self.myDictionary = {'first':0, 'second':0}
def addItem[self, key, numToAdd]:
self.myDictionary[key] += numToAdd
numOfFoos = 2
listOfFoos = []
for num in range[0, numOfFoos]:
listOfFoos.append[Foo[]]
listOfFoos[0].addItem['first', 1]
listOfFoos[0].addItem['first', 2]
listOfFoos[1].addItem['first', 2]
print " This is the value of foo1 it should be 3"
print listOfFoos[0].myDictionary
print "This is the value of foo2 ot should be 2"
print listOfFoos[1].myDictionary
6, nó sẽ không trả về giá trị biến lớp thực tế.Để tránh điều này, luôn luôn sửa đổi giá trị biến lớp bằng cách sử dụng tên lớp để tất cả các đối tượng có được giá trị cập nhật. Như thế này
class Fleet:
""" Stores Fleet Numbers, Represents a fleet """
shipNamesandNumber = {}
def addShip[self, type, numToAdd]:
self.shipNamesandNumber[ships.shipTypesDict[type]['type']] += numToAdd
2