Chuyển tới nội dung
Home » Static And Class Methods In Python | Class Method Properties

Static And Class Methods In Python | Class Method Properties

Python OOP Tutorial 3: classmethods and staticmethods

5.2.Accessing StaticInstance Fields¶

One common error new Java coders encounter reads something like non-static variable cannot be referenced from a static context. This occurs when a static method tries to call an instance variable.

Why can’t we do this? Static methods can be called from anywhere (depending on their access modifier), and they do NOT require us to create an object for a particular class. However, these methods must be independent of any values unique to a particular object.

For example, if we have a

Circle

class, then we can define and call a
static

area

method without creating a new object:

Circle.area(radius)

. Since the area of a circle is just,

PI*radius*radius

, we can pass in the argument when we call the method. The
method does not depend on any value stored within a specific

Circle

object.

Now let’s assume we define a

Car

class with an instance variable for

color

. The value of this field will NOT be the same for every

Car

object we create. Thus, trying to call a static method like

Car.printColor()

results in an error. Since there is no single value for

color

that applies to every object, trying to access it from outside of the
class does not work. To print the color of a

Car

object, we must call the
method on that specific object:

myCar.printColor()

.

Instance fields can only be called by instance methods.

Note

While static methods cannot access instance variables, an instance method CAN access a static variable. Why?

What are the differences between Classmethod and StaticMehtod?

Class Method Static Method
The class method takes cls (class) as first argument. The static method does not take any specific parameter.
Class method can access and modify the class state. Static Method cannot access or modify the class state.
The class method takes the class as parameter to know about the state of that class. Static methods do not know about class state. These methods are used to do some utility tasks by taking some parameters.
@classmethod decorator is used here. @staticmethod decorator is used here.

The Static methods are used to do some utility tasks, and class methods are used for factory methods. The factory methods can return class objects for different use cases.

Python OOP Tutorial 3: classmethods and staticmethods
Python OOP Tutorial 3: classmethods and staticmethods

Python3


class


MyClass:


def


__init__(


self


, value):


self


.value


value


def


get_value(


self


):


return


self


.value


obj


MyClass(


10


print


(obj.get_value())

Static method:-

What is Static Method in Python?

A static method is a method that is tied to the class instead of the class’s object. It is not possible to pass an implicit first argument to a static method. The class state cannot be accessed or changed by this method. It is present in a class because having the method in a class makes sense.

Syntax of Python Static Method:

Below is the syntax for using the Static Method in python:

Return Value:

It returns a Static method for the function.

Class Methods, Static Methods, & Instance Methods EXPLAINED in Python
Class Methods, Static Methods, & Instance Methods EXPLAINED in Python

What is the Static Method in Python?

A static method does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.

Syntax Python Static Method:

class C(object):
@staticmethod
def fun(arg1, arg2, …):

returns: a static method for function fun.

What is Class Method in Python?

The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as an implicit first argument, just like an instance method receives the instance

Syntax Python Class Method:

class C(object):
@classmethod
def fun(cls, arg1, arg2, …):
….
fun: function that needs to be converted into a class method
returns: a class method for function.

  • A class method is a method that is bound to the class and not the object of the class.
  • They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
  • It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that will be applicable to all the instances.
Python staticmethod and classmethod
Python staticmethod and classmethod

When To Use Static Methods

It’s a little more difficult to come up with a good example here. But tell you what, I’ll just keep stretching the pizza analogy thinner and thinner… (yum!)

Here’s what I came up with:


import math class Pizza: def __init__(self, radius, ingredients): self.radius = radius self.ingredients = ingredients def __repr__(self): return (f'Pizza({self.radius!r}, ' f'{self.ingredients!r})') def area(self): return self.circle_area(self.radius) @staticmethod def circle_area(r): return r ** 2 * math.pi

Now what did I change here? First, I modified the constructor and

__repr__

to accept an extra

radius

argument.

I also added an

area()

instance method that calculates and returns the pizza’s area (this would also be a good candidate for an

@property

— but hey, this is just a toy example).

Instead of calculating the area directly within

area()

, using the well-known circle area formula, I factored that out to a separate

circle_area()

static method.

Let’s try it out!


>>> p = Pizza(4, ['mozzarella', 'tomatoes']) >>> p Pizza(4, ['mozzarella', 'tomatoes']) >>> p.area() 50.26548245743669 >>> Pizza.circle_area(4) 50.26548245743669

Sure, this is a bit of a simplistic example, but it’ll do alright helping explain some of the benefits that static methods provide.

As we’ve learned, static methods can’t access class or instance state because they don’t take a

cls

or

self

argument. That’s a big limitation — but it’s also a great signal to show that a particular method is independent from everything else around it.

In the above example, it’s clear that

circle_area()

can’t modify the class or the class instance in any way. (Sure, you could always work around that with a global variable but that’s not the point here.)

Now, why is that useful?

Flagging a method as a static method is not just a hint that a method won’t modify class or instance state — this restriction is also enforced by the Python runtime.

Techniques like that allow you to communicate clearly about parts of your class architecture so that new development work is naturally guided to happen within these set boundaries. Of course, it would be easy enough to defy these restrictions. But in practice they often help avoid accidental modifications going against the original design.

Put differently, using static methods and class methods are ways to communicate developer intent while enforcing that intent enough to avoid most slip of the mind mistakes and bugs that would break the design.

Applied sparingly and when it makes sense, writing some of your methods that way can provide maintenance benefits and make it less likely that other developers use your classes incorrectly.

Static methods also have benefits when it comes to writing test code.

Because the

circle_area()

method is completely independent from the rest of the class it’s much easier to test.

We don’t have to worry about setting up a complete class instance before we can test the method in a unit test. We can just fire away like we would testing a regular function. Again, this makes future maintenance easier.

Key Takeaways

  • Instance methods need a class instance and can access the instance through

    self

    .
  • Class methods don’t need a class instance. They can’t access the instance (

    self

    ) but they have access to the class itself via

    cls

    .
  • Static methods don’t have access to

    cls

    or

    self

    . They work like regular functions but belong to the class’s namespace.
  • Static and class methods communicate and (to a certain degree) enforce developer intent about class design. This can have maintenance benefits.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods

  • Trending Categories
  • Data Structure
  • Networking
  • RDBMS
  • Operating System
  • Java
  • MS Excel
  • iOS
  • HTML
  • CSS
  • Android
  • Python
  • C Programming
  • C++
  • C#
  • MongoDB
  • MySQL
  • Javascript
  • PHP
  • Physics
  • Chemistry
  • Biology
  • Mathematics
  • English
  • Economics
  • Psychology
  • Social Studies
  • Fashion Studies
  • Legal Studies
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer’s Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

Class method vs static method in Python

The class method in Python is a method, which is bound to the class but not the object of that class. The static methods are also same but there are some basic differences. For class methods, we need to specify @classmethod decorator, and for static method @staticmethod decorator is used.

Syntax for Class Method.

class my_class: @classmethod deffunction_name(cls, arguments): #Function Body return value

Syntax for Static Method.

class my_class: @staticmethod deffunction_name(arguments): #Function Body return value

Intermediate Python Tutorial #2 - Static and Class Methods
Intermediate Python Tutorial #2 – Static and Class Methods

What is Class Method in Python?

The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as an implicit first argument, just like an instance method receives the instance

Syntax Python Class Method:

class C(object):
@classmethod
def fun(cls, arg1, arg2, …):
….
fun: function that needs to be converted into a class method
returns: a class method for function.

  • A class method is a method that is bound to the class and not the object of the class.
  • They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
  • It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that will be applicable to all the instances.

Delicious Pizza Factories With @classmethod

If you’ve had any exposure to pizza in the real world you’ll know that there are many delicious variations available:


Pizza(['mozzarella', 'tomatoes']) Pizza(['mozzarella', 'tomatoes', 'ham', 'mushrooms']) Pizza(['mozzarella'] * 4)

The Italians figured out their pizza taxonomy centuries ago, and so these delicious types of pizzas all have their own names. We’d do well to take advantage of that and give the users of our

Pizza

class a better interface for creating the pizza objects they crave.

A nice and clean way to do that is by using class methods as factory functions for the different kinds of pizzas we can create:


class Pizza: def __init__(self, ingredients): self.ingredients = ingredients def __repr__(self): return f'Pizza({self.ingredients!r})' @classmethod def margherita(cls): return cls(['mozzarella', 'tomatoes']) @classmethod def prosciutto(cls): return cls(['mozzarella', 'tomatoes', 'ham'])

Note how I’m using the

cls

argument in the

margherita

and

prosciutto

factory methods instead of calling the

Pizza

constructor directly.

This is a trick you can use to follow the Don’t Repeat Yourself (DRY) principle. If we decide to rename this class at some point we won’t have to remember updating the constructor name in all of the classmethod factory functions.

Now, what can we do with these factory methods? Let’s try them out:


>>> Pizza.margherita() Pizza(['mozzarella', 'tomatoes']) >>> Pizza.prosciutto() Pizza(['mozzarella', 'tomatoes', 'ham'])

As you can see, we can use the factory functions to create new

Pizza

objects that are configured the way we want them. They all use the same

__init__

constructor internally and simply provide a shortcut for remembering all of the various ingredients.

Another way to look at this use of class methods is that they allow you to define alternative constructors for your classes.

Python only allows one

__init__

method per class. Using class methods it’s possible to add as many alternative constructors as necessary. This can make the interface for your classes self-documenting (to a certain degree) and simplify their usage.

#53 Python Tutorial for Beginners | Types of Methods
#53 Python Tutorial for Beginners | Types of Methods

Class method vs Static Method

The difference between the Class method and the static method is:

  • A class method takes cls as the first parameter while a static method needs no specific parameters.
  • A class method can access or modify the class state while a static method can’t access or modify it.
  • In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
  • We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.

Class method vs Static method in Python

In Python, there are two types of methods that are used within classes: class methods and static methods. While both types of methods have similar syntax, they are used for different purposes.

Class methods are methods that are bound to the class rather than an instance of the class. They are defined using the @classmethod decorator, which takes the class as its first argument, traditionally named cls, rather than the instance of the class, which is traditionally named self. Class methods are typically used when the method needs to access or modify class-level attributes or when the method needs to create new instances of the class.

Static methods, on the other hand, are methods that are not bound to either the class or the instance of the class. They are defined using the @staticmethod decorator, which takes no special arguments. Static methods are typically used when the method does not depend on either the class or the instance of the class and does not modify any class-level attributes.

Here are some key differences between class methods and static methods:

Access to class-level attributes

Class methods can access and modify class-level attributes. They have access to the class object and can modify class variables or create new instances of the class. Static methods, on the other hand, do not have access to the class object and cannot modify any class-level attributes.

Access to instance-level attributes

Class methods do not have access to instance-level attributes. They can only modify class-level attributes or create new instances of the class. Static methods, similarly, do not have access to instance-level attributes and cannot modify them.

Bound to the class or instance

Class methods are bound to the class and are typically called on the class itself, rather than on an instance of the class. They can also be called on an instance of the class, but in that case, the instance is automatically passed as the first argument. Static methods, on the other hand, are not bound to either the class or an instance of the class. They can be called on the class or on an instance of the class, but they do not have any access to either the class or the instance.

Inheritance

Class methods can be overridden in subclasses, and they will behave like regular instance methods in the subclass. Static methods, on the other hand, cannot be overridden in subclasses and will behave the same way as they do in the base class.

Here’s an example to illustrate the difference between class methods and static methods:

class MyClass: class_variable = 0 def __init__(self, instance_variable): self.instance_variable = instance_variable @classmethod def class_method(cls, x): cls.class_variable += x @staticmethod def static_method(x): return x obj = MyClass(5) MyClass.class_method(1) obj.class_method(2) print(MyClass.class_variable) # Output: 3 obj.static_method(3) MyClass.static_method(4)

In the above example, class_variable is a class-level attribute, and instance_variable is an instance-level attribute. The class_method is a class method, and the static_method is a static method. class_method modifies the class-level attribute, while static_method simply returns its argument.

When the class method class_method is called on the class MyClass, it increments the value of class_variable by the argument x. When it is called on an instance of the class obj, it behaves the same way but has the instance obj automatically passed as the first argument.

As mentioned earlier, class methods are defined using the @classmethod decorator. They take the class itself as the first argument, which is typically named cls. This argument is used to access class-level attributes and methods. Class methods are often used as alternative constructors or factory methods that create new instances of the class. They can be called on both the class and the instance, but when called on the instance, the instance is automatically passed as the first argument.

Here’s an example of a class method that acts as an alternative constructor:

class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_birth_year(cls, name, birth_year): age = 2023 – birth_year return cls(name, age) person1 = Person(‘Alice’, 25) person2 = Person.from_birth_year(‘Bob’, 1990) print(person1.name, person1.age) # Output: Alice 25 print(person2.name, person2.age) # Output: Bob 33

In the above example, we have a Person class with an __init__ method that takes name and age as arguments. We also have a class method from_birth_year that takes name and birth_year as arguments. This method calculates the age based on the birth year and returns a new Person instance with the given name and age. Note that we use cls instead of Person to create the new instance, which allows the method to work even if the class name is changed later.

When we create person1 using the regular __init__ method, we pass in the name and age directly. When we create person2 using the from_birth_year method, we pass in the name and birth year, and the method calculates the age for us.

Static Methods

Static methods are defined using the @staticmethod decorator. They do not take any special arguments like class methods and are not bound to either the class or the instance. They are often used as utility functions that do not depend on any state from either the class or the instance.

Here’s an example of a static method that checks if a string is a palindrome:

class StringUtils: @staticmethod def is_palindrome(string): return string == string[::-1] print(StringUtils.is_palindrome(‘racecar’)) # Output: True print(StringUtils.is_palindrome(‘hello’)) # Output: False

In the above example, we have a StringUtils class with a static method is_palindrome that takes a string as an argument and returns True if it is a palindrome and False otherwise. Since this method does not depend on any state from the class or the instance, it is defined as a static method.

When we call the is_palindrome method on the StringUtils class, we pass in a string and it returns True if it is a palindrome and False otherwise. For a more brief explanation of Class method vs Static method in Python visit our original article on – Class method vs Static method in Python

Conclusion

In conclusion, class methods and static methods are both useful in Python programming. Class methods are used when we need to access or modify class-level attributes, or when we need to create new instances of the class. Static methods are used when we have a utility function that does not depend on any state from the class or the instance. By understanding the differences between these two types of methods, we can choose the right tool for the job and write more efficient and effective code.

In the end, I will like to say Thank you for taking the time to read this article on encapsulation in Python. We hope that you found it informative and useful. If you have any questions or doubts about the topic, please feel free to leave a comment below. We would be happy to clarify any concepts or ideas that you may find confusing. Thanks again for reading!

References

LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG PYTHON #3: CLASS METHOD AND STATIC METHOD
LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG PYTHON #3: CLASS METHOD AND STATIC METHOD

Static Method vs Class Method

The Difference between Class Method and Static method is stated below.

  • While a static method requires no specific parameters, a class method takes cls as its first argument.
  • While a static method cannot access or modify the class state, a class method can.
  • Static methods are typically unaware of the class state. They are utility methods that operate on some parameters after receiving them. On the other hand, class must be a parameter for class methods.
  • Python’s @classmethod decorator and @staticmethod decorator are used to create class methods and static methods, respectively.

When do we use Class Methods and Static Methods

  • To create factory methods, we typically use the class method. For various use cases, factory methods return class objects that resemble constructors.
  • To create utility functions, we frequently use static methods.

How to Define and Use Class Methods and Static Methods

For Defining a class method, we use @classmethod decorator and for defining a static method, we use @staticmethod decorator.

For understanding them better, lets take a look at an example in which we are using both the class method and static method.

Example: Using Class methods and static methods

Output:

Python3


class


geeks:


course


'DSA'


def


purchase(obj):


print


"Purchase course : "


, obj.course)


geeks.purchase


classmethod


(geeks.purchase)


geeks.purchase()

Output

Purchase course : DSA

Create class method using classmethod()

Created print_name classmethod before creating this line print_name() It can be called only with an object not with the class now this method can be called as classmethod print_name() method is called a class method.

Python OOP Tutorial (Object Orientated Programming ) - Static Methods and Class Methods
Python OOP Tutorial (Object Orientated Programming ) – Static Methods and Class Methods

Class Methods

Class methods are methods within a class that only have access to class variables and other class methods. They are passed the name of the class and therefore can access anything within the class. Like static methods they cannot access any instance attributes. You can create a class method by using the “@classmethod” decorator.


class myClass: count = 0 def __init__(self): self.x = x @classmethod def classMethod(cls): cls.count += 1 # The classMethod can access and modify class variables. It takes the class name as a required parameter

Please refer to the video for further explanation and more detailed examples.

By Shubham

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this quick post, we will learn how to create and use a Python static method. We will also have a look at what advantages and disadvantages static methods offer as compared to the instance methods. Let’s get started.

Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class. This also means that static methods cannot modify the state of an object as they are not bound to it. Let’s see how we can create static methods in Python.

Python Static methods can be created in two ways. Let’s see each of the ways here:

Let’s directly jump to sample code snippet on how to use the

staticmethod()

approach:


class Calculator: def addNumbers(x, y): return x + y # create addNumbers static method Calculator.addNumbers = staticmethod(Calculator.addNumbers) print('Product:', Calculator.addNumbers(15, 110))

Note that we called the addNumbers we created without an object. When we run this program, here is the output we will get: There were no surprises there. This approach is controlled as at each place, it is possible to create a static method out of a class method as well. Let’s see another approach with the same example here.

This is a more subtle way of creating a Static method as we do not have to rely on a statement definition of a method being a class method and making it static at each place you make it static. Let’s use this annotation in a code snippet:


class Calculator: # create addNumbers static method @staticmethod def addNumbers(x, y): return x + y print('Product:', Calculator.addNumbers(15, 110))

When we run this program, here is the output we will get: This was actually a much better way to create a static method as the intention of keeping the method static is clear as soon as we create it and mark it with the

@staticmethod

annotation.

Static methods have a very clear use-case. When we need some functionality not w.r.t an Object but w.r.t the complete class, we make a method static. This is pretty much advantageous when we need to create Utility methods as they aren’t tied to an object lifecycle usually. Finally, note that in a static method, we don’t need the

self

to be passed as the first argument. API Reference: Python Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Amazing explanation

– BitchBark

Actually, this example works even if the @staticmethod decorator is removed. However, if the class had a mixture of static and non-static methods then the decorator would be necessary.

– Ken

good explanation

– himanshu

Good explanation! But the method is called multiplyNums, but, actually, it is summing the numbers?!

– WA

Thanks …! Wonderful explanation.

– Shweta

What does w.r.t mean?

– Mike

Why are you adding the numbers in the first example?

– A Discord User#4063

Click below to sign up and get $200 of credit to try our products over 60 days!

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Exploring the Differences Between Class Methods and Static Methods in Python

Class method vs Static Method

The difference between the Class method and the static method is:

  • A class method takes cls as the first parameter while a static method needs no specific parameters.
  • A class method can access or modify the class state while a static method can’t access or modify it.
  • In general, static methods know nothing about the class state. They are utility-type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as a parameter.
  • We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.
Static Methods in Python | Python Tutorial - Day #65
Static Methods in Python | Python Tutorial – Day #65

Class method

Class method ngầm gán class cho tham số thứ nhất khi gọi hàm. Và điều này luôn đúng dù nó được gọi từ instance hay class.


>>> Foo.class_bar('args') executing class_bar(

, args) >>> foo.class_bar('args') executing class_bar(

, args)


Sự vi diệu này có được nhờ decorator

@classmethod

. Chính decorator này đã biến đổi phương thức

__get__

của class method. Một minh họa cho phương thức

__get__

như sau:


class ClassMethod(object): "Emulate PyClassMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, klass=None): if klass is None: klass = type(obj) def newfunc(*args): return self.f(klass, *args) return newfunc

Python3


class


MyClass:


def


__init__(


self


, value):


self


.value


value


@staticmethod


def


get_max_value(x, y):


return


max


(x, y)


obj


MyClass(


10


print


(MyClass.get_max_value(


20


30


))


print


(obj.get_max_value(


20


30


))

Below is the complete Implementation

Python @staticmethod vs @classmethod - What's the difference?
Python @staticmethod vs @classmethod – What’s the difference?

Example code

from datetime import date as dt class Employee: def __init__(self, name, age): self.name = name self.age = age @staticmethod defisAdult(age): if age > 18: return True else: return False @classmethod defemp_from_year(emp_class, name, year): return emp_class(name, dt.today().year – year) def __str__(self): return ‘Employee Name: {} and Age: {}’.format(self.name, self.age) e1 = Employee(‘Dhiman’, 25) print(e1) e2 = Employee.emp_from_year(‘Subhas’, 1987) print(e2) print(Employee.isAdult(25)) print(Employee.isAdult(16))

How to define a class method and a static method?

To define a class method in python, we use @classmethod decorator, and to define a static method we use @staticmethod decorator. Let us look at an example to understand the difference between both of them. Let us say we want to create a class Person. Now, python doesn’t support method overloading like C++ or Java so we use class methods to create factory methods. In the below example we use a class method to create a person object from birth year.

As explained above we use static methods to create utility functions. In the below example we use a static method to check if a person is an adult or not.

One simple Example :

class method:

Functions vs Classes: When to Use Which and Why?
Functions vs Classes: When to Use Which and Why?

Python3


class


Student:


name


"Geeksforgeeks"


def


print_name(obj):


print


"The name is : "


, obj.name)


Student.print_name


classmethod


(Student.print_name)


Student.print_name()

Output

The name is : Geeksforgeeks

Factory method using a Class method

Uses of classmethod() function are used in factory design patterns where we want to call many functions with the class name rather than an object.

5.2.Instance Methods¶

As we learned in the last chapter, instance methods define the behaviors that are unique or specialized to each class. Every object created from a class will carry a copy of these methods.

Instance methods depend on the data stored in an individual object. If two objects call the same method, the results will vary when the objects contain different data.

Let’s add a couple more instance methods to our

Student

class.

What are the behaviors that our

Student

class should have? To start, it
makes sense that when a student takes a class and earns a grade, their data
should be updated accordingly. Additionally, it would be nice to easily
identify the grade level of a student—freshman, sophomore, junior, or senior.

The framework for these new methods is shown in the

Student

class below,
but each method is missing some code. Filling in that code is left for you to
do in the chapter exercises.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

public class Student { private static int nextStudentId = 1; private String name; private int studentId; private int numberOfCredits; private double gpa; public Student(String name, int studentId, int numberOfCredits, double gpa) { this.name = name; this.studentId = studentId; this.numberOfCredits = numberOfCredits; this.gpa = gpa; } public Student(String name, int studentId) { this(name, studentId, 0, 0); } public Student(String name) { this(name, nextStudentId); nextStudentId++; } public String studentInfo() { return (this.name + ” has a GPA of: ” + this.gpa); } public void addGrade(int courseCredits, double grade) { // Update the appropriate fields: numberOfCredits, gpa } public String getGradeLevel() { // Determine the grade level of the student based on numberOfCredits } /* getters and setters omitted */ }

Tip

When creating your classes, think about the behaviors that you want to make available, as well as the access level of those methods.

Lecture 8 : OOPS in Python | Object Oriented Programming | Classes & Objects | Python Full Course
Lecture 8 : OOPS in Python | Object Oriented Programming | Classes & Objects | Python Full Course

Python3


from


datetime


import


date


class


Person:


def


__init__(


self


, name, age):


self


.name


name


self


.age


age


@staticmethod


def


from_FathersAge(name, fatherAge, fatherPersonAgeDiff):


return


Person(name, date.today().year


fatherAge


fatherPersonAgeDiff)


@classmethod


def


from_BirthYear(


cls


, name, birthYear):


return


cls


(name, date.today().year


birthYear)


def


display(


self


):


print


self


.name


"'s age is: "


str


self


.age))


class


Man(Person):


sex


'Female'


man


Man.from_BirthYear(


'John'


1985


print


isinstance


(man, Man))


man1


Man.from_FathersAge(


'John'


1965


20


print


isinstance


(man1, Man))

Example of classmethod in Python

Create a simple classmethod

In this example, we are going to see how to create a class method in Python. For this, we created a class named “Geeks” with a member variable “course” and created a function named “purchase” which prints the object. Now, we passed the method

Geeks.purchase

into a class method using the

@classmethod

decorator, which converts the method to a class method. With the class method in place, we can call the function “purchase” without creating a function object, directly using the class name “Geeks.”

CS403 Final Term Preparation 2024 | CS403P Final Term Preparation
CS403 Final Term Preparation 2024 | CS403P Final Term Preparation

5.2.Static Methods¶

We’ve already used static methods quite a bit in this course, all the way back to our first Java method:

public static void main(String[] args) {}

Now let’s examine them in the context of what we’ve recently learned about classes.

Just like static fields, static methods belong to the class as a whole, and not to any of the specific instances of the class. Thus, they are sometimes also called class methods. A static method is essentially the opposite of an instance method, since the two cases are mutually exclusive. Instance methods rely on each object’s specific data, while static methods must NOT rely on data from a specific object.

We call a static method by preceding it with the class name and using dot-notation. Here’s an example that we looked at previously.

Examples


HelloMethods.java

1 2 3 4 5 6 7 8

public class HelloMethods { public static void main(String[] args) { String message = Message.getMessage(“fr”); System.out.println(message); } }


Message.java

1 2 3 4 5 6 7 8 9 10 11 12 13

public class Message { public static String getMessage(String lang) { if (lang.equals(“sp”)) { return “¡Hola, Mundo!”; } else if (lang.equals(“fr”)) { return “Bonjour, le monde!”; } else { return “Hello, World!”; } } }

The call occurs in line 4:

Message.getMessage("fr")

. We call the static

getMessage

without needing an instance of the

Message

class. Instead,
we use the name of the class itself.

Warning

It is technically allowed to call a static method using an instance of a
class:

myObject.someStaticMethod()

. However, best practice recommends
using the class name instead:

ClassName.someStaticMethod()

. This makes
it clear to other coders that you are calling a static method.

A method should be static when it does NOT refer to any instance fields of the containing class (it may refer to static fields, however). These methods tend to be utility-like (e.g. carrying out a calculation, or using or fetching some external resource).

Python3


from


datetime


import


date


class


Person:


def


__init__(


self


, name, age):


self


.name


name


self


.age


age


@classmethod


def


fromBirthYear(


cls


, name, year):


return


cls


(name, date.today().year


year)


@staticmethod


def


isAdult(age):


return


age >


18


person1


Person(


'mayank'


21


person2


Person.fromBirthYear(


'mayank'


1996


print


(person1.age)


print


(person2.age)


print


(Person.isAdult(


22


))

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
17 Nov, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: OOP Method Types in Python: @classmethod vs @staticmethod vs Instance Methods

In this tutorial I’ll help demystify what’s behind class methods, static methods, and regular instance methods.

If you develop an intuitive understanding for their differences you’ll be able to write object-oriented Python that communicates its intent more clearly and will be easier to maintain in the long run.

Free Bonus: Click here to get access to a free Python OOP Cheat Sheet that points you to the best tutorials, videos, and books to learn more about Object-Oriented Programming with Python.

What is missing from current AI?
What is missing from current AI?

Python3


from


datetime


import


date


class


Person:


def


__init__(


self


, name, age):


self


.name


name


self


.age


age


@classmethod


def


fromBirthYear(


cls


, name, year):


return


cls


(name, date.today().year


year)


@staticmethod


def


isAdult(age):


return


age >


18


person1


Person(


'mayank'


21


person2


Person.fromBirthYear(


'mayank'


1996


print


(person1.age)


print


(person2.age)


print


(Person.isAdult(


22


))

Output:

21
25
True

Auxiliary Space: O(1)

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
30 Dec, 2022

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Python: instance method vs class method vs static method

This post hasn’t been updated for 2 years

Bài viết gốc: https://manhhomienbienthuy.github.io/2017/10/25/python-instance-method-vs-class-method-vs-static-method.html (đã xin phép tác giả

)

Trong lập trình hướng đối tượng nói chung instance method và class method đều rất quan trọng. Một số ngôn ngữ như Python cung cấp thêm một loại method nữa là static method. Trong bài viết này, chúng ta sẽ tìm hiểu các loại phương này trong ngôn ngữ Python.

Mở đầu

Hãy xem xét ví dụ là một class sau để hiểu rõ hơn về các loại phương thức này:


>>> class Foo: ... def instance_bar(self, x): ... print("executing instance_bar(%s, %s)" % (self, x)) ... @classmethod ... def class_bar(cls, x): ... print("executing class_bar(%s, %s)" % (cls, x)) ... @staticmethod ... def static_bar(x): ... print("executing static_bar(%s)" % x) ... >>> foo = Foo()

Dưới đây là cách đơn giản nhất để thực thi một phương thức:


>>> foo.instance_bar('args') executing instance_bar(<__main__.Foo object at 0x7fef22567518>, args)

Đây là một instance method, là phương thức phổ biến nhất. Một đối tượng (instance của class) được ngầm truyền thành tham số thứ nhất (

self

) của phương thức này.

Class method là phương thức thuộc về cả class. Khi thực thi, nó không dùng đến bất cứ một instance nào của class đó. Thay vào đó, cả class sẽ được truyền thành tham số thứ nhất (

cls

) của phương thức này:


>>> Foo.class_bar('args') executing class_bar(

, args)

Một điều thú vị là class method cũng có thể gọi từ instance mà không gặp trở ngại gì (nhiều ngôn ngữ vẫn cho làm điều này kèm theo vài warning).


>>> foo.class_bar('args') executing class_bar(

, args)

Static method là một phương thức đặc biệt, nó không sử dụng bất cứ thứ gì liên quan đến class hay instance của class đó. Cả

self

hay

cls

đều không xuất hiện trong tham số của loại phương thức này. Và static method hoạt động không khác gì một hàm thông thường.


>>> foo.static_bar('args') executing static_bar(args) >>> Foo.static_bar('args') executing static_bar(args)

Về cơ bản, phương thức cũng giống như hàm. Tuy nhiên,

instance_bar

là một instance method, và khi bạn gọi

foo.instance_bar

thì Python sẽ ngầm truyền

foo

thành tham số thứ nhất của phương thức đó. Và

foo.instance_bar

không còn là hàm nguyên gốc ban đầu mà là một phiên bản đã được “bind” cho

foo

.


>>> foo.instance_bar

Vì vậy, mặc dù

instance_bar

cần hai tham số, nhưng

foo.instance_bar

chỉ cần một tham số thôi.

Tương tự với class method,

Foo.class_bar

thì class

Foo

được ngầm gán cho tham số thứ nhất của

class_bar

. Ngay cả khi gọi từ instance,

foo.class_bar

thì class

Foo

vẫn được gán cho

class_bar

.


>>> Foo.class_bar

> >>> foo.class_bar

Riêng static method là trường hợp đặc biệt, mặc dù nó là một phương thức nhưng dù gọi

foo.static_bar

hay

Foo.static_bar

thì kết quả trả về vẫn là hàm ban đầu không hề được “bind” bất cứ một đối tượng nào.


>>> foo.static_bar

>>> Foo.static_bar

Python đã lưu trữ vào thực hiện tất cả việc “bind” này như thế nào?

Trước hết, toàn bộ các phương thức này đều được lưu trữ trong

__dict__

của class.


>>> Foo.__dict__ mappingproxy({'__weakref__':

, '__module__': '__main__', 'class_bar':

, '__doc__': None, 'static_bar':

, '__dict__':

, 'instance_bar':

})





Vì vậy, mọi tham chiếu đến các loại phương này đều sẽ thông qua

__dict__

.

Mặt khác, Python có một loại đối tượng rất thú vị, thích hợp để áp dụng cho những đối tượng cần “bind” gọi là descriptor. Hiểu đơn giản, descriptor là những đối tượng có ít nhất một trong các phương thức sau:


  • __get__

  • __set__

  • __delete__

Bằng việc cài đặt các phương thức này, một đối tượng có thể thay đổi hoạt động của chúng khi được tham chiếu.

Và các phương thức chính là descriptor. Chúng ta những descriptor đặc biệt, chỉ có phương thức

__get__

, và cũng nhờ phương thức này là hoạt động của chúng cũng rất đặc biệt.

Khi chúng ta định nghĩa một class, các phương thức được định nghĩa như function thông thường, nhưng Python tự thêm

__get__

cho chúng để có thể gọi về sau. Nhờ đó, các phương thức khi được gọi sẽ có thể được “bind” các đối tượng tương ứng.

Hãy nhìn lại một chút về quá trình tham chiếu thuộc tính của instance.

Theo như sơ đồ, khi chúng ta gọi

foo.instance_bar

chúng ta sẽ nhận được

Foo.__dict__['instance_bar'].__get__(foo, Foo)


>>> foo.instance_bar

> >>> Foo.__dict__['instance_bar'].__get__(foo, Foo)

Và dưới đây là quá trình tham chiếu thuộc tính của class.

Và, khi chúng ta gọi

Foo.class_bar

chúng ta sẽ nhận được

Foo.__dict__['class_bar'].__get__(None, Foo)


>>> Foo.class_bar

> >>> Foo.__dict__['class_bar'].__get__(None, Foo)

Việc tham chiếu khá đơn giản, tuy nhiên, mọi sự vi diệu của các phương thức đều nhờ

__get__

mà ra cả. Nó vi diệu tới mức chúng ta có thể gọi instance method từ class mà không gặp vấn đề gì.


>>> Foo.instance_bar(1, 2) executing instance_bar(1, 2)

Tất nhiên là trong lập trình hướng đối tượng, chắc không ai làm trò này.

What is the Static Method in Python?

A static method does not receive an implicit first argument. A static method is also a method that is bound to the class and not the object of the class. This method can’t access or modify the class state. It is present in a class because it makes sense for the method to be present in class.

Syntax Python Static Method:

class C(object):
@staticmethod
def fun(arg1, arg2, …):

returns: a static method for function fun.

ALL 11 LIST METHODS IN PYTHON EXPLAINED
ALL 11 LIST METHODS IN PYTHON EXPLAINED

Static Methods

Static methods are methods within a class that have no access to anything else in the class (no self keyword or cls keyword). They cannot change or look at any object attributes or call other methods within the class. They can be thought of as a special kind of function that sits inside of the class. When we create a static method we must use something called a decorator. The decorator for a static method is “@staticmethod”.


class myClass: def __init__(self): self.x = x @staticmethod def staticMethod(): return "i am a static method" # Notice staticMethod does not require the self parameter

Các bài viết liên quan

Hành Trình Đào Tạo Doanh Nghiệp 365 Ngày Cùng MCI: Tổng Kết và Chia Sẻ

Trải qua một năm đầy thách thức và học hỏi, 365 ngày đầy ý nghĩa và khát vọng của MCI Việt Nam, nơi mà chúng tôi không chỉ đào tạo, mà còn đồng hành cùng các doanh nghiệp Việt, đặc biệt là trong lĩnh vực quan trọng – Phân tích Dữ liệu.

Case study: Ứng dụng của Python trong Digital Marketing

Python càng ngày được sử dụng rất phổ biến, đặc biệt là đối với Digital marketing vì có rất nhiều lý do giúp cho ngành này tăng trưởng. Một trong những lý do là hệ sinh thái mạnh, bao gồm hàng triệu người dùng, framework và hướng dẫn. Digital marketing đã tiếp cận, trở nên tinh vi và hướng dữ liệu được hỗ trợ bằng nhiều công cụ kinh doanh thông minh khác.

SQL và Python là gì? Bắt đầu học Data Analyst nên học công cụ nào trước?

SQL hay Python? Công cụ nào quan trọng hơn? Nên học công cụ nào trước?

OOP Class Inheritance and Private Class Members - Python for Beginners!
OOP Class Inheritance and Private Class Members – Python for Beginners!

Python3


from


datetime


import


date


class


Person:


def


__init__(


self


, name, age):


self


.name


name


self


.age


age


@classmethod


def


fromBirthYear(


cls


, name, year):


return


cls


(name, date.today().year


year)


@staticmethod


def


isAdult(age):


return


age >


18


person1


Person(


'mayank'


21


person2


Person.fromBirthYear(


'mayank'


1996


print


(person1.age)


print


(person2.age)


print


(Person.isAdult(


22


))

Output:

21
25
True

Auxiliary Space: O(1)

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
30 Dec, 2022

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

5.Instance and Static Methods¶

We explored configuring data within classes with fields and properties. Now let’s turn our attention back to class behavior (methods).

Static method

Static method là phương thức không phụ thuộc gì vào instance hay class. Vì vậy, phương thức

__get__

của nó khá đơn giản, nó chỉ đơn giản trả về bản thân hàm đó là đủ.


class StaticMethod(object): "Emulate PyStaticMethod_Type() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): return self.f

Classes and Objects with Python - Part 1 (Python Tutorial #9)
Classes and Objects with Python – Part 1 (Python Tutorial #9)

Class Method vs Static Method

The basic difference between the class method vs Static method in Python and when to use the class method and static method in Python.

5.2.Quick Method Review¶

In the last chapter, we learned that:

  1. A method belongs to a class and performs an action.

  2. Methods cannot stand on their own—they must be part of a class.

  3. To call a method on an object, use dot notation:

    objectName.methodName(arguments);

  4. Access modifiers apply to methods:


    1. private

      methods as those that are NOT useful outside of the class but contribute internally to helping the class behave as desired or expected.

    2. public

      methods contain code that other classes need to use when they implement the class containing those methods. Make methods

      public

      only when you expect other classes to use them, and when you are committed to maintaining those methods for other programs.

Let’s take a closer look at two different types of methods—both of which we have used in earlier examples.

Object-oriented Programming (OOP) in Python (Easy to Understand Guide) #20
Object-oriented Programming (OOP) in Python (Easy to Understand Guide) #20

Python3


class


MyClass:


def


__init__(


self


, value):


self


.value


value


@staticmethod


def


get_max_value(x, y):


return


max


(x, y)


obj


MyClass(


10


print


(MyClass.get_max_value(


20


30


))


print


(obj.get_max_value(


20


30


))

Below is the complete Implementation

Class Method Properties

Spring Boot & Spring Data JPA – Complete Course
Spring Boot & Spring Data JPA – Complete Course

5.2.Check Your Understanding¶

Question

Assume that we add two methods to a

Pet

class—

public String makeNoise()

and

public static void increaseAge()

. Which of the following statements is
true?

  1. The


    makeNoise()

    method can be accessed outside of the

    Pet

    class, while the

    increaseAge()

    method cannot.

  2. Each


    Pet

    object carries a copy of the

    makeNoise()

    method but NOT a copy of the

    increaseAge()

    method.

  3. The


    increaseAge()

    method can be accessed outside of the

    Pet

    class, while the

    makeNoise()

    method cannot.

  4. Each


    Pet

    object carries a copy of the

    increaseAge()

    method but NOT a copy of the

    makeNoise()

    method.

Question

Explain why it IS possible for an instance method to access a static field.

The classmethod() is an inbuilt function in Python, which returns a class method for a given function.

Python3


class


MyClass:


def


__init__(


self


, value):


self


.value


value


def


get_value(


self


):


return


self


.value


obj


MyClass(


10


print


(obj.get_value())

Static method:-

{Python Classes & Objects} - [#28 الفئات و الكائنات في بايثون - [ تعلم بايثون بالعربي
{Python Classes & Objects} – [#28 الفئات و الكائنات في بايثون – [ تعلم بايثون بالعربي

Instance, Class, and Static Methods — An Overview

Let’s begin by writing a (Python 3) class that contains simple examples for all three method types:


class MyClass: def method(self): return 'instance method called', self @classmethod def classmethod(cls): return 'class method called', cls @staticmethod def staticmethod(): return 'static method called'

NOTE: For Python 2 users: The


@staticmethod

and

@classmethod

decorators are available as of Python 2.4 and this example will work as is. Instead of using a plain

class MyClass:

declaration you might choose to declare a new-style class inheriting from

object

with the

class MyClass(object):

syntax. Other than that you’re good to go.

Instance Methods

The first method on

MyClass

, called

method

, is a regular instance method. That’s the basic, no-frills method type you’ll use most of the time. You can see the method takes one parameter,

self

, which points to an instance of

MyClass

when the method is called (but of course instance methods can accept more than just one parameter).

Through the

self

parameter, instance methods can freely access attributes and other methods on the same object. This gives them a lot of power when it comes to modifying an object’s state.

Not only can they modify object state, instance methods can also access the class itself through the

self.__class__

attribute. This means instance methods can also modify class state.

Class Methods

Let’s compare that to the second method,

MyClass.classmethod

. I marked this method with a

@classmethod

decorator to flag it as a class method.

Instead of accepting a

self

parameter, class methods take a

cls

parameter that points to the class—and not the object instance—when the method is called.

Because the class method only has access to this

cls

argument, it can’t modify object instance state. That would require access to

self

. However, class methods can still modify class state that applies across all instances of the class.

Static Methods

The third method,

MyClass.staticmethod

was marked with a

@staticmethod

decorator to flag it as a static method.

This type of method takes neither a

self

nor a

cls

parameter (but of course it’s free to accept an arbitrary number of other parameters).

Therefore a static method can neither modify object state nor class state. Static methods are restricted in what data they can access – and they’re primarily a way to namespace your methods.

Khi nào nên dùng static method

Static method, với sự đặc biệt của nó, được dùng rất hạn chế. Bởi vì nó không giống như instance method hay class method, nó không có bất cứ sự liên quan tới đối tượng gọi nó. Static method không phải là phương thức được sử dụng thường xuyên.

Tuy nhiên, nó vẫn tồn tại là có lý do của nó. Static method thường dùng để nhóm các hàm tiện ích lại với nhau (trong cùng một class). Nó không yêu cầu gì từ class đó, ngoại trừ việc tham chiếu khi được gọi.

Nhưng hàm như vậy không cho vào class nào cũng không vấn đề gì. Nhưng nhóm chúng trong class và gọi chúng thông quan instance hoặc class sẽ giúp chúng ta hiểu hơn về bối cảnh cũng như chức năng của chúng.

Nếu bạn cảm thấy những lợi ích trên từ việc sử dụng static method, hãy sử dụng nó. Còn không, hãy dùng hàm và module như thông thường.

Kết luận

Instace method, class method, static method là những khái niệm rất cơ bản trong lập trình hướng đối tượng với Python. Nắm vững khái niệm cũng như bối cảnh sử dụng chúng sẽ giúp chúng ta code đẹp hơn rất nhiều.

All Rights Reserved

In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python.

Class Method Vs Static Method in Python
Class Method Vs Static Method in Python

Instance method

Instance method có phương thức

__get__

và nó sẽ ngầm truyền tham số thứ nhất của

__get__

thành tham số thứ nhất của phương thức. Chúng ta có thể minh họa quá trình này với đoạn code như sau:


class Function: "Simulate func_descr_get() in Objects/funcobject.c" def __init__(self, f): self.f = f def __get__(self, obj, objtype=None): if obj is None: return self.f def newfunc(*args): return self.f(obj, *args) return newfunc

Chúng ta có thể nhìn rõ quá trình thực thi

__get__

như sau:


>>> # Truy cập thông qua __dict__ không gọi __get__ ... Foo.__dict__['instance_bar']

>>> # Goị instance từ class có thực hiện tham chiếu và gọi __get__ ... # Nhưng vì truyền None cho tham số thứ nhất nên kết quả vẫn là hàm ban đầu ... Foo.instance_bar

>>> # Truy cập từ instance sẽ gọi phương thức __get__ ... # và kết quả là hàm đã được bind ... foo.instance_bar

> >>> # hàm được bind vẫn giữ các giá trị hàm ban đầu ... foo.instance_bar.__func__



Python3


from


datetime


import


date


class


Person:


def


__init__(


self


, name, age):


self


.name


name


self


.age


age


@classmethod


def


fromBirthYear(


cls


, name, year):


return


cls


(name, date.today().year


year)


def


display(


self


):


print


"Name : "


self


.name,


"Age : "


self


.age)


person


Person(


'mayank'


21


person.display()

Output

Name : mayank Age : 21

How the class method works for the inheritance?

In this example, we are making Python class hierarchy with two classes,

Person

and

Man

, and demonstrates the usage of class methods and inheritance.

What are static methods in Python and when to use them?
What are static methods in Python and when to use them?

How to define a class method and a static method?

To define a class method in python, we use @classmethod decorator, and to define a static method we use @staticmethod decorator. Let us look at an example to understand the difference between both of them. Let us say we want to create a class Person. Now, python doesn’t support method overloading like C++ or Java so we use class methods to create factory methods. In the below example we use a class method to create a person object from birth year.

As explained above we use static methods to create utility functions. In the below example we use a static method to check if a person is an adult or not.

One simple Example :

class method:

Let’s See Them In Action!

I know this discussion has been fairly theoretical up to this point. And I believe it’s important that you develop an intuitive understanding for how these method types differ in practice. We’ll go over some concrete examples now.

Let’s take a look at how these methods behave in action when we call them. We’ll start by creating an instance of the class and then calling the three different methods on it.


MyClass

was set up in such a way that each method’s implementation returns a tuple containing information for us to trace what’s going on — and which parts of the class or object the method can access.

Here’s what happens when we call an instance method:


>>> obj = MyClass() >>> obj.method() ('instance method called',

This confirmed that

method

(the instance method) has access to the object instance (printed as ) via the

self

argument.

When the method is called, Python replaces the

self

argument with the instance object,

obj

. We could ignore the syntactic sugar of the dot-call syntax (

obj.method()

) and pass the instance object manually to get the same result:


>>> MyClass.method(obj) ('instance method called',

Can you guess what would happen if you tried to call the method without first creating an instance?

By the way, instance methods can also access the class itself through the

self.__class__

attribute. This makes instance methods powerful in terms of access restrictions – they can modify state on the object instance and on the class itself.

Let’s try out the class method next:


>>> obj.classmethod() ('class method called',

Calling

classmethod()

showed us it doesn’t have access to the object, but only to the object, representing the class itself (everything in Python is an object, even classes themselves).

Notice how Python automatically passes the class as the first argument to the function when we call

MyClass.classmethod()

. Calling a method in Python through the dot syntax triggers this behavior. The

self

parameter on instance methods works the same way.

Please note that naming these parameters

self

and

cls

is just a convention. You could just as easily name them

the_object

and

the_class

and get the same result. All that matters is that they’re positioned first in the parameter list for the method.

Time to call the static method now:


>>> obj.staticmethod() 'static method called'

Did you see how we called

staticmethod()

on the object and were able to do so successfully? Some developers are surprised when they learn that it’s possible to call a static method on an object instance.

Behind the scenes Python simply enforces the access restrictions by not passing in the

self

or the

cls

argument when a static method gets called using the dot syntax.

This confirms that static methods can neither access the object instance state nor the class state. They work like regular functions but belong to the class’s (and every instance’s) namespace.

Now, let’s take a look at what happens when we attempt to call these methods on the class itself – without creating an object instance beforehand:


>>> MyClass.classmethod() ('class method called',

) >>> MyClass.staticmethod() 'static method called' >>> MyClass.method() TypeError: unbound method method() must be called with MyClass instance as first argument (got nothing instead)

We were able to call

classmethod()

and

staticmethod()

just fine, but attempting to call the instance method

method()

failed with a

TypeError

.

And this is to be expected — this time we didn’t create an object instance and tried calling an instance function directly on the class blueprint itself. This means there is no way for Python to populate the

self

argument and therefore the call fails.

This should make the distinction between these three method types a little more clear. But I’m not going to leave it at that. In the next two sections I’ll go over two slightly more realistic examples for when to use these special method types.

I will base my examples around this bare-bones

Pizza

class:


class Pizza: def __init__(self, ingredients): self.ingredients = ingredients def __repr__(self): return f'Pizza({self.ingredients!r})'


>>> Pizza(['cheese', 'tomatoes']) Pizza(['cheese', 'tomatoes'])

Note: This code example and the ones further along in the tutorial use Python 3.6 f-strings to construct the string returned by


__repr__

. On Python 2 and versions of Python 3 before 3.6 you’d use a different string formatting expression, for example:Python

def __repr__(self): return 'Pizza(%r)' % self.ingredients

Learn Python in Arabic #108 - OOP Part 6 - Class Methods And Static Methods
Learn Python in Arabic #108 – OOP Part 6 – Class Methods And Static Methods

Python @classmethod Decorator

The @classmethod decorator is a built-in function decorator which is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

Syntax of classmethod Decorator

class C(object):

@classmethod

def fun(cls, arg1, arg2, …):

….

Where,

  • fun: the function that needs to be converted into a class method
  • returns: a class method for function.

Note:

  • A class method is a method that is bound to the class and not the object of the class.
  • They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
  • It can modify a class state that would apply across all the instances of the class. For example, it can modify a class variable that would be applicable to all instances.

Example

In the below example, we use a staticmethod() and classmethod() to check if a person is an adult or not.

What is Class Method in Python?

The built-in function decorator @classmethod is an expression that is evaluated just after the definition of your function. The result of such a evaluation casts a shadow over your function definition. Similar to how an instance method receives the instance, a class method also takes the class as an implicit first argument.

Syntax of Python Class Method:

Below is the syntax for using the Class Method in python:

Return Value:

It returns a Class method for the function.

Static and Class Methods | Python Tutorials For Beginners
Static and Class Methods | Python Tutorials For Beginners

Phân Biệt 02 Hàm Static Method Trong Python Và Hàm Class Method Trong Python

Xin chào bạn. Trong chuyên mục lần này MCI sẽ giúp các bạn phân biệt giữa hàm Static method trong python và hàm Class method trong Python. Nếu chúng ta phát triển sự hiểu biết trực quan về sự khác biệt của những hàm trên, chúng ta có thể viết Python hướng đối tượng truyền đạt ý định của nó rõ ràng hơn và sẽ dễ duy trì hơn về lâu dài.

Nội dung bài viết

Static Method trong python là gì?

MyClass.static method được đánh dấu bằng decorator @staticmethod để gắn cờ nó là một static method.

Loại phương thức này không nhận tham số self hay cls (nhưng tất nhiên có thể miễn phí chấp nhận một số lượng tùy ý các tham số khác).

Do đó, một phương thức tĩnh không thể sửa đổi trạng thái đối tượng cũng như trạng thái lớp. Các phương thức tĩnh bị hạn chế về dữ liệu mà chúng có thể truy cập – và chúng chủ yếu là một cách để tạo không gian tên cho các phương thức của bạn.

Static method trong python bản chất vẫn là những method được liên kết với một class chứ. Và nó có ưu điểm là không phụ thuộc vào trạng thái của đối tượng.

Cú pháp của hàm staticmethod() trong Python

Cú pháp:

class C(object):

@staticmethod

def fun(arg1, arg2, …):

returns: a static method for function fun.

  • Static method trong python là một phương thức được liên kết với lớp chứ không phải đối tượng của lớp.
  • Static method không thể truy cập hoặc sửa đổi trạng thái lớp.
  • Nó hiện diện trong một lớp vì nó có ý nghĩa đối với phương thức hiện diện trong lớp.

Tham số của hàm Static Method trong python

Hàm staticmethod() chỉ có một tham số duy nhất:

  • Hàm: Hàm cần được chuyển thành một static method

Giá trị trả về của hàm staticmethod()

Hàm staticmethod() trả về một static method cho một hàm tham số mà bạn đưa vào.

Class Method trong python là gì?

Decorator của @classmethod là hàm tích hợp, là một biểu thức được đánh giá sau khi hàm của bạn được xác định. Kết quả của đánh giá đó làm mờ định nghĩa chức năng của bạn.

Một Class Method như một đối số đầu tiên ngầm định, giống như một instance method.

Cú pháp:

lớp C (đối tượng):

@classmethod

def fun (cls, arg1, arg2, …):

….

fun: hàm cần được chuyển đổi thành một Class Method trong python

Return: một class method cho hàm.

Class Method trong python là một phương thức được liên kết với class chứ không phải đối tượng của Class..

Chúng có quyền truy cập vào trạng thái của Class vì class method nhận một tham số class parameter trỏ đến class của nó chứ không phải đối tượng của class.

Các Class Method trong python có thể sửa đổi, áp dụng cho tất cả các trường hợp của class. Ví dụ. Ví dụ như nó có thể sửa đổi một biến class sẽ được áp dụng cho tất cả các trường hợp.

Sự khác biệt giữa Class Method và Static Method trong python

Class method sẽ lấy cls làm tham số đầu tiên trong static method không cần tham số cụ thể.

Một Class method có thể truy cập hoặc sửa đổi trạng thái class trong khi một static method không thể truy cập hoặc sửa đổi nó.

Nói chung, các static method không biết gì về trạng thái của class. Chúng là các method kiểu tiện ích ( utility type methods) nhận một số tham số và hoạt động dựa trên các tham số đó. – Mặt khác, các method của class method phải có class là một tham số.

Chúng ta sử dụng @classmethod decorator trong python để tạo một class method và chúng tôi sử dụng @staticmethod decorator để tạo một static method trong python.

Sử dụng static method hay class method trong những trường hợp nào

Thông thường. mọi người sử dụng class method để tạo các factory methods. Các factory methods trả về các đối tượng lớp (tương tự như một phương thức khởi tạo) cho các trường hợp sử dụng khác nhau.

Sử dụng các static method để tạo các utility functions (Hàm tiện ích)

Làm thế nào để định nghĩa static method và class method

Để xác định một class method trong python, chúng ta cần sử dụng @classmethod decorator và để xác định một static method, chúng ta sử dụng @staticmethod decorator.

Chúng ta hãy cùng xem xét một ví dụ để hiểu sự khác biệt giữa cả hai. Giả sử chúng ta muốn tạo một Class Person. Hiện tại, python không hỗ trợ nạp chồng phương thức như C ++ hoặc Java, vì vậy chúng ta cần sử dụng các class method để tạo các factory methods. Trong ví dụ dưới đây, chúng ta sử dụng một class method để tạo một đối tượng người từ năm sinh.

Như đã giải thích ở trên, chúng ta sử dụng các static method để tạo các utility functions (hàm tiện ích). Trong ví dụ dưới đây, chúng ta sử dụng Static method để kiểm tra xem một người có phải là người lớn hay không.


Ví dụ: # python program to demonstrate # use of class method and static method from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age # a class method to create a Person object by birth year. @classmethod def fromBirthYear(cls, name, year): return cls(name, date.today().year - year) # a static method to check if a Person is adult or not. @staticmethod def isAdult(age): return age > 18 person1 = Person('My Anh', 21) person2 = Person.fromBirthYear('My Anh', 1996) print (person1.age) print (person2.age) # print the result print (Person.isAdult(22)) Output: 21 25 True

Chia sẻ của MCI về Static và Class method sẽ kết thúc tại đây, mong rằng thông qua bài viết các bạn đã hiểu hơn về 2 method này và dễ dàng ứng dụng hơn. Các bạn nhớ theo dõi MCI để nhận được nhiều kiến thức hơn nha!

Bạn cũng có thể tham khảo thêm về khoá học Python cơ bản đến nâng cao tại MCI để tìm cho mình lộ trình học hiệu quả hơn nhé.

Các khóa học
  • Data Engineer Track Specialized
  • Combo Data Engineering Professional Hot
  • Advanced AWS Cloud Data Engineer Specialized
  • AWS Data Engineer for Beginners Specialized
  • Combo Data Engineering Foundations Specialization Hot
  • Combo Python Level 1 & Level 2 Bestseller
  • Business Intelligence Track Hot
  • Data Analyst with Python Track Bestseller
  • Python Foundation in Data Analytics Bestseller
  • RPA UiPath Nâng Cao: Chiến Thuật Automation Cho Chuyên Gia Specialized
  • RPA UiPath cho Người Mới Bắt Đầu: Thành Thạo Automation Chỉ Trong 1 Ngày Specialized
  • IT Business Analyst Fast Track Bestseller
  • Combo IT Business Analyst Level 1 & Level 2 Bestseller
  • IT Business Analyst for Beginners Bestseller
Đăng ký tư vấn khóa học

*Vui lòng nhập số điện thoại của bạn

*Vui lòng nhập họ tên của bạn

*Vui lòng chọn giới tính

*Vui lòng chọn 1 trường

Keywords searched by users: static and class methods in python

Python Instance Vs Static Vs Class Method Differences - Youtube
Python Instance Vs Static Vs Class Method Differences – Youtube
Python Classmethod Vs Staticmethod | Learn The Top Differences
Python Classmethod Vs Staticmethod | Learn The Top Differences
Python Static Method - Askpython
Python Static Method – Askpython
Python Class Method Explained With Examples – Pynative
Python Class Method Explained With Examples – Pynative
Class Method Vs Static Method In Python - Youtube
Class Method Vs Static Method In Python – Youtube
Staticmethod In Python - Askpython
Staticmethod In Python – Askpython

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *