Python vs Ruby class methods [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The following two Ruby and Python codes are examples of class methods. Why does python allow accessing class methods through objects but ruby doesn't ?
Python code
class student:
b = 78
#classmethod
def foo(var):
return var.b
z = student()
print z.foo() # => 78
Ruby Code
class Student
##b = 78
def self.foo
##b
end
end
z = Student.new
puts z.foo # => -e:20:in `<main>': undefined method `foo' for #<Student:0x007ff4f98ab9e8> (NoMethodError)

An answer for the ruby side of your question: Ruby does allow accessing class methods through objects via a reader for the class:
class Student
##b = 78
def self.foo
##b
end
end
z = Student.new
puts z.class.foo
z.class returns the class of the object (in this case it is Student).
class Student
end
z = Student.new
puts z.class #Student
puts z.class.class #Class

From Ruby doc Object#display:
display(port=$>)
Prints obj on the given port (default $>). Equivalent to:
def display(port=$>)
port.write self
end
So it just displays the receiver, which is a Student instance. I don't see how this is relevant to class methods.
Calling the class method Student.display is in fact possible:
z.class.display

Ruby doesn't have class methods, only instance methods. In your case, foo is in instance method of the singleton class of Student.
Once you understand that there is no such thing as a class method in Ruby, only instance methods, it should be immediately obvious why calling an instance on a completely different instance cannot possibly work.

Related

Is it a good practice to implement a singleton-like class using class attributes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I have a class that contains some variables/states.
I would like to share those states with many other classes in my code.
I looked online and I saw that modules and singleton classes are a good way to this. I ended up creating a class and storing all the data as class attributes and accessing it via the class it self, like the example:
# foo.py
class Foo(object):
varx=45
def foo(x):
Foo.varx = x
And I would import the data as:
# bar.py
from foo import Foo
print(Foo.varx) #45
Foo.foo(5)
print(Foo.varx) #5
I would like to know if using classes attributes like this is an anti-pattern, or if there is a downside I am not seeing in this implementation.
Since your foo method is altering the state of the class Foo (rather than the state of any one instance of Foo), it would be more pythonic to use a classmethod in this case. Also, note that there is no need to explicitly inherit from object, as all python classes implicitly inherit from object.
class Foo:
varx = 45
#classmethod
def foo(cls, x):
cls.varx = x
Your current implementation of the foo method has the name of the class hardcoded into the implementation, which means that the implementation would break if you changed the name of the class. The implementation would also break if you had another class inheriting from Foo which you wanted to be able to implement the methods of Foo, as the class inheriting from Foo would have a different name.

Can you access attributes that were created with the init method from other methods in the class? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
When I write the __init__ method and assign attributes, can I access those attributes in other methods (functions) that I write in that class? If so, how is it done?
I've googled this but couldn't find an answer. I Haven't been able to wrap my head around this one.
Use self:
class MyClass:
def __init__(self):
self.name = 'John'
def other_method(self):
print(self.name)
other_method will print "John".
When you make a class and set an instance (like first_class = MyClass()) the def __init__(self): is run or initialised. Any variables in there, like self.name are able to be accessed from within the class and its functions, as well as when you use a class in another program. self kinda attaches that variable to that class.
Basically using Allure's example:
class MyClass:
def __init__(self):
self.name = "John"
def show_name(self):
print(self.name)
Then use MyClass's name outside of class, in a program:
firstClass = MyClass()#Initialise MyClass and its variables
print(firstClass.name)
Or:
firstClass= MyClass()
firstClass.show_name()
Both output:
'John'
(still putting up this answer for others, hope you don't mind :) )

class A :, class A(object) :, or class A() : [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
What is the exact difference among these three and when do we use what?
class A:
pass
class A(object):
pass
or
class A():
pass
class A:
pass
It is implicitly subclass of object (as in other cases). I think it's most prefereable in case you don't inherit from anything (but it can depend on coding standards).
2)
class A(object):
pass
It is most explicit version.
3)
class A():
pass
In this case, as no class passed as parent class, by default it inherits from object.
So from functionality point of view, there is no difference. In Python3, all clasess inherit from object (even if it's not explixitly declared).
However, if you are using Python2, you need to pass superclass explicitly in every case.

What the purpose of creating class instance attibutes directly in the code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Pyhon allows to create any class instance attribute just like new variable and you don't need to define them in class definition.
What's the purpose of that?
class MyClass:
def __init__(self):
pass
obj = MyClass()
obj.a = '1';
print(obj.a)
#>> 1
P.S.
found interesting example of such kind of usage
Can you use a string to instantiate a class
There dynamically created attributes used to store dynamically instatiated classes
The purpose of this is simplicity: There is no difference to accessing an instance inside or outside of a method. The object seen inside and outside of a method is completely equivalent, and by extension the same rules apply anywhere:
class MyClass:
def __init__(self):
print(self) # <__main__.MyClass object at 0x119636490>
self.b = 12 # assign to an instance
obj = MyClass()
print(obj) # <__main__.MyClass object at 0x119636490>
obj.b = 12 # # assign to an instance
Note that one can read and write attributes inside and outside methods, and these attributes are visible inside and outside of methods. In fact, Python has no concept of "inside" and "outside" of methods, aside from a few code-rewrites such as double-underscore name mangling.
This is both a result and the enabling feature to allow various inbuilt features of other languages to work without explicit support. For example, Python allows the equivalent of extension methods without extra syntax/functionality:
class MyPoint:
def __init__(self, x, y):
self.x, self.y = x, y
# Oops, forgot a repr!
def my_point_repr(self):
return f'{self.__class__.__name__}(x={self.x}, y={self.y})'
MyPoint.__repr__ = my_point_repr
print(MyPoint(1, 2)) # MyPoint(x=1, y=2)

use functions in a class - python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a couple of functions defined in my code and I want to be able to call them in one of my class.
I want to pass one of their name as an argument so I can select the right function to call in my class.
I looked for such things on internet but what I found is how to call a function defined in a class inside the same or another class. I can't define my functions inside my class because they also call other functions
So there's not too much but there's my code :
class _fonction_use_:
def __init__(self,pos,function):
self.pos=pos
self.function=function
Where "function" would be the name of one of my functions defined outside the class.
So, if fonction_use belong to this class, I want something like fonction_use.function to return the function I would assigned it before.
Since functions are first class objects, you can pass them directly to your class.
def somefunc():
pass # do something
class MyClass(object):
def __init__(self, pos, function):
self.pos = pos
self.function = function
myclass = MyClass(0, somefunc)

Categories