- calling class/static method from class variable in python
- Статические переменные и методы в Python
- Что такое статическая переменная Python?
- Доступ к статической переменной с использованием того же объекта класса
- Статический метод
- Особенности статических методов
- Использование метода staticmethod()
- Использование декоратора @staticmethod
- Доступ к статическому методу с использованием того же объекта класса
- Функция возвращает значение с помощью статического метода
- python class variable in static method
- 4 Answers 4
calling class/static method from class variable in python
I’m trying to make a ImageLoader class handle the loading and processing of image resources like this:
class ImageLoader: TileTable = __loadTileTable('image path', some other variable) @staticmethod def _loadTileTable(arg1, arg2): blah blah
however, on compile i get: NameError: name ‘_loadTileTable’ is not defined If i replace the second line with TileTable = ImageLoader.__loadTileTable(‘image path’, some other variable) then i get NameError: name ‘ImageLoader’ is not defined As i’m going from C# to Python, static classes with static methods is what i’d use to implement this. However, i’m open to how I’d do this in general in python (that is, call static library functions that are only grouped together by their functionality). UPDATE: After reading both answers, I’m getting a picture that what i’m trying to do probably isn’t right. How would I go about imlementing ImageLoader so that I can do this: Assuming that tile table returned an array module1.py
aTile = ImageLoader.TileTable[1]
anotherTile = ImageLoader.TileTable[2]
ideally, i’d populate TileTable just once. Update: Thanks for all the answers, I found my last answer to populating TileTable just once in the python modules doco
«A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module is imported somewhere»
Статические переменные и методы в Python
Статическая переменная и статический метод – это широко используемые концепции программирования на различных языках, таких как C ++, PHP, Java и т. l. Эти переменные и методы принадлежат классу и объектам. В этом разделе мы узнаем, как создать статические переменные и методы в Python.
Что такое статическая переменная Python?
Когда мы объявляем переменную внутри класса, но вне метода, она называется статической переменной или переменной класса. Ее можно вызвать непосредственно из класса, но не через экземпляры класса. Однако статические переменные сильно отличаются от других членов и не конфликтуют с тем же именем переменной в программе Python.
Давайте рассмотрим программу, демонстрирующую использование статических переменных в Python.
class Employee: # create Employee class name dept = 'Information technology' # define class variable def __init__(self, name, id): self.name = name # instance variable self.id = id # instance variable # Define the objects of Employee class emp1 = Employee('John', 'E101') emp2 = Employee('Marcus', 'E105') print(emp1.dept) print(emp2.dept) print(emp1.name) print(emp2.name) print(emp1.id) print(emp2.id) # Access class variable using the class name print(Employee.dept) # print the department # change the department of particular instance emp1.dept = 'Networking' print(emp1.dept) print(emp2.dept) # change the department for all instances of the class Employee.dept = 'Database Administration' print(emp1.dept) print(emp2.dept)
Information technology Information technology John Marcus E101 E105 Information technology Networking Information technology Networking Database Administration
В приведенном выше примере dept – это переменная класса, определенная вне методов класса и внутри определения класса. Где имя и идентификатор – это переменная экземпляра, определенная внутри метода.
Доступ к статической переменной с использованием того же объекта класса
Мы можем напрямую обращаться к статической переменной в Python, используя тот же объект класса с оператором точки.
Давайте рассмотрим программу для доступа к статической переменной в Python с использованием того же объекта класса.
class Car: # define the class variable or static variable of class Car num = 7 msg = 'This is a good Car.' # create the object of the class obj = Car() # Access a static variable num using the class name with a dot operator. print("Lucky No.", Car.num) print(Car.msg)
Lucky No. 7 This is a good Car
Статический метод
Python имеет статический метод, принадлежащий классу. Это похоже на статическую переменную, которая привязана к классу, а не к объекту класса. Статический метод можно вызвать без создания объекта для класса.
Это означает, что мы можем напрямую вызвать статический метод со ссылкой на имя класса. Более того, статический метод ограничен классом; следовательно, он не может изменить состояние объекта.
Особенности статических методов
Ниже приведены особенности статического метода:
- Статический метод в Python связан с классом.
- Его можно вызвать непосредственно из класса по ссылке на имя класса.
- Он не может получить доступ к атрибутам класса в программе Python.
- Привязан только к классу. Таким образом, он не может изменить состояние объекта.
- Он также используется для разделения служебных методов для класса.
- Может быть определен только внутри класса, но не для объектов класса.
- Все объекты класса используют только одну копию статического метода.
Есть два способа определить статический метод в Python:
Использование метода staticmethod()
Staticmethod() – это встроенная функция в Python, которая используется для возврата заданной функции как статического метода.
Staticmethod() принимает единственный параметр. Где переданный параметр – это функция, которую необходимо преобразовать в статический метод.
Давайте рассмотрим программу для создания функции как статического метода с использованием staticmethod() в Python.
class Marks: def Math_num(a, b): # define the static Math_num() function return a + b def Sci_num(a, b): # define the static Sci_num() function return a +b def Eng_num(a, b): # define the static Eng_num() function return a +b # create Math_num as static method Marks.Math_num = staticmethod(Marks.Math_num) # print the total marks in Maths print(" Total Marks in Maths" , Marks.Math_num(64, 28)) # create Sci_num as static method Marks.Sci_num = staticmethod(Marks.Sci_num) # print the total marks in Science print(" Total Marks in Science" , Marks.Sci_num(70, 25)) # create Eng_num as static method Marks.Eng_num = staticmethod(Marks.Eng_num) # print the total marks in English print(" Total Marks in English" , Marks.Eng_num(65, 30))
Total Marks in Maths 92 Total Marks in Science 95 Total Marks in English 95
В приведенной выше программе мы объявили метод Math_num, метод Sci_num и метод Eng_num как статический метод вне класса с помощью функции staticmethod(). После этого мы можем вызвать статический метод напрямую, используя имя класса Marks.
Использование декоратора @staticmethod
@Staticmethod – это встроенный декоратор, который определяет статический метод внутри класса. Он не получает никаких аргументов в качестве ссылки на экземпляр класса или класс, вызывающий сам статический метод.
class Abc: @staticmethod def function_name(arg1, arg2, ?): # Statement to be executed Returns: a static method for function function_name
Примечание. @Staticmethod – это современный подход к определению метода как статического, и большая часть программистов использует этот подход в программировании на Python.
Давайте создадим программу для определения статического метода с помощью декоратора @staticmethod в Python.
class Marks: @staticmethod def Math_num(a, b): # define the static Math_num() function return a + b @staticmethod def Sci_num(a, b): # define the static Sci_num() function return a +b @staticmethod def Eng_num(a, b): # define the static Eng_num() function return a +b # print the total marks in Maths print(" Total Marks in Maths" , Marks.Math_num(64, 28)) # print the total marks in Science print(" Total Marks in Science" , Marks.Sci_num(70, 25)) # print the total marks in English print(" Total Marks in English" , Marks.Eng_num(65, 30))
Total Marks in Maths 92 Total Marks in Science 95 Total Marks in English 95
Доступ к статическому методу с использованием того же объекта класса
Рассмотрим программу для доступа к статическому методу класса с помощью @staticmethod в Python.
class Test: # define a static method using the @staticmethod decorator in Python. @staticmethod def beg(): print("Welcome to the World!! ") # create an object of the class Test obj = Test() # call the static method obj.beg()
Функция возвращает значение с помощью статического метода
Напишем программу для возврата значения с помощью метода @static в Python.
class Person: @staticmethod def Age (age): if (ageThe person is not eligible to vote.python class variable in static method
[updated]: Full code I always get confused with pyhton's staticmethods but according to this (last answer), it should work! getting error:class MyConnection: def __init__(self, hostname, port, user, password): myhostname = hostname myport = port myuser = user mypassword = password isisessid = None @staticmethod def connect(): my_session = MyConnection() headers = headers['Authorization'] = 'Basic ' + string.strip( base64.encodestring(MyConnection.myuser + ':' + MyConnection.mypassword)) body = json.dumps() uri = '/session/1/session' connection = httplib.HTTPSConnection(MyConnection.myhostname, MyConnection.myport) connection.connect() try: connection.request('POST', uri, body, headers) response = connection.getresponse() my_session.isisessid = MyConnection.extract_session_id( response.getheaders()) except Exception, e: print e connection.close() except httplib.BadStatusLine, e: print e connection.close() return my_session
This question has nothing to do with static methods. The error is in your __init__ : stackoverflow.com/a/18622179/429533
@spinus: Thanks for the suggestion, its not my code - trying to build a car without reinventing the wheels! 😉
4 Answers 4
If the attributes are going to be static, don't initialize them in the initializer method, declare them outside at the class level, not at method level.
But why are you initializing class attributes in the initializer? every instance that you create will overwrite their values!
I believe you're confusing what instance attributes and class attributes are used for. Why don't you try using only instance attributes? all things considered, having static data is not a good idea. For example:
class MyConnection: def __init__(self, hostname, port, user, password): self.myhostname = hostname self.myport = port self.myuser = user self.mypassword = password @staticmethod def connect(): my_session = MyConnection() print my_session.myuser # just an example
Im creating an instance of class "my_session = MyConnection()" so I should use it to get its variables. duhh
You have to define attributes in a class scope (static attributes) or in instance scope (in __init__ ).
So in class scope it looks like:
class Cls(object): class_scope_attribute = 1 @staticmethod def method1(): print Cls.class_scope_attribute @classmethod def metdho2(cls): print cls.class_scope_attribute def method3(self): print Cls.class_scope_attribute print self.__class__.class_scope_attribute
class Cls2(object): def __init__(self): self.instance_scope_attribute @staticmethod def method1(): # cannot access the instance_scope_attribute pass @classmethod def method2(cls): # cannot access the instance_scope_attribute pass def method3(self): print self.instance_scope_attribute
Look at the self in __init__ before variable name.
So, you have to add self. or move variables to class scope, but be careful as class scope attributes are shared by all instances.
If your purpose is really to make connect a @staticmethod , then initialize myhostname , myport , myuser , and mypassword at the class level, like in:
class MyConnection: myhostname= hostnameValue myport= portValue myuser= userValue mypassword= passwordValue @staticmethod def connect(): my_session = MyConnection() headers = headers['Authorization'] = 'Basic ' + string.strip( base64.encodestring( MyConnection.myuser + ':' + MyConnection.mypassword ) ) body = json.dumps() my_session.connection = httplib.HTTPSConnection(MyConnection.myhostname, MyConnection.myport) my_session.connection.connect() MyConnection.connect()
Alternatively, you can leave them in None and give them a value before calling connect() .
If you want to make connect an instance method, then you are pretty much there. You just need to remove decorator @staticmethod , and do a few other changes:
class MyConnection: def __init__(self, hostname, port, user, password): self.myhostname = hostname self.myport = port self.myuser = user self.mypassword = password def connect(): headers = headers['Authorization'] = 'Basic ' + string.strip( base64.encodestring(self.myuser + ':' + self.mypassword) ) body = json.dumps() connection = httplib.HTTPSConnection(self.myhostname, self.myport) connection.connect() my_session= MyConnection(hostnameValue,portValue,userValue,passwordValue) my_session.connect()