下面是一个简单的Python程序,它使用单个方法创建一个类。
# A simple example class
class Test:
# A sample method
def fun(self):
print("Hello")
# Driver code
obj = Test()
obj.fun()
正如我们在上面所看到的,我们使用class语句和类的名称创建一个新类。接下来是一个缩进的语句块,它构成了类的主体。在这种情况下,我们在类中定义了一个方法。
接下来,我们使用类的名称后跟一对括号创建此类的对象/实例。
当我们将此对象的方法称为myobject.method(arg1,arg2)时,Python会自动将其转换为MyClass.method(myobject,arg1,arg2) - 这就是所有特殊的自我。
类和实例变量(或属性)
在Python中,实例变量是其值在构造函数或方法中使用self分配的变量。
类变量是其值在类中赋值的变量。
# Python program to show that the variables with a value
# assigned in class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.
# Class for Computer Science Student
class CSStudent:
# Class Variable
stream = 'cse'
# The init method or constructor
def __init__(self, roll):
# Instance Variable
self.roll = roll
# Objects of CSStudent class
a = CSStudent(101)
b = CSStudent(102)
print(a.stream) # prints "cse"
print(b.stream) # prints "cse"
print(a.roll) # prints 101
# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"
我们也可以在普通方法中定义实例变量。
# Python program to show that we can create
# instance variables inside methods
# Class for Computer Science Student
class CSStudent:
# Class Variable
stream = 'cse'
# The init method or constructor
def __init__(self, roll):
# Instance Variable
self.roll = roll
# Adds an instance variable
def setAddress(self, address):
self.address = address
# Retrieves instance variable
def getAddress(self):
return self.address
# Driver Code
a = CSStudent(101)
a.setAddress("Noida, UP")
print(a.getAddress())
三个资料Q群下载不了也转发不了,先放这里Fine_tuning.zipLangChain.zipdata_clear.rar