473,795 Members | 2,875 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class level variables in Python

I am just starting to learn the OO side of Python scripting, and I am
a little confused on the following. Take the following example class:
class rectangle(objec t): z = 1
def __init__(self):
self.x = 2
r = rectangle()
print r.z 1 print r.x 2 r.z = 16
print r.z 16 r.x = 17
print r.x 17


I was wondering if someone could explain if there is any difference
between initalizing your object attributes up in the __init__
constructor or setting them up as (I am guessing at the name here)
object level variables (like z)

thanks

-- brian
Jul 18 '05 #1
3 2481

"Brian Munroe" <bm*****@tribad or.nu> wrote in message
news:c1******** *************** ***@posting.goo gle.com...
I am just starting to learn the OO side of Python scripting, and I am a little confused on the following. Take the following example class:
class rectangle(objec t): z = 1
def __init__(self):
self.x = 2
r = rectangle()
print r.z 1 print r.x 2 r.z = 16
print r.z 16 r.x = 17
print r.x 17


I was wondering if someone could explain if there is any difference
between initalizing your object attributes up in the __init__
constructor or setting them up as (I am guessing at the name here)
object level variables (like z)


Everything set at 'top' level under the class statement is a class
attribute. Ditto for anything set outside the class statement as
someclass.attri bute. This include instance methods, which are common
to all instances and therefore *attributes* of the class.

Everything set within instance methods as self.attribute or outside as
someinstance.at tribute are instance attributes private to that
instance. Just as a function can have a private local variable with
the same name as a 'public' global variable, an instance can have an
attribute of the same name as an attribute of its class. Just as
function locals 'mask' the global of the same name, instance 'locals'
usually* mask the class attribute of the same name.

In your example above, you start with class attribute z and later add
an r instance attribute of same name (but different value). First you
see one, then the other.

(* I believe the masking exception alluded to above has something to
do with special methods, descriptors, and classes derived from
builtins, but I do not know the current rule will enough to even quote
it. But beginners usually need not worry about it.)

Terry J. Reedy
Jul 18 '05 #2
"Brian Munroe" <bm*****@tribad or.nu> wrote in message
news:c1******** *************** ***@posting.goo gle.com...
I was wondering if someone could explain if there is any difference
between initalizing your object attributes up in the __init__
constructor or setting them up as (I am guessing at the name here)
object level variables (like z)


Hi.
Yes there is a difference. One is an instance attribute, the other is a
class attribute:
class C: .... attr = 1
.... def __init__(self):
.... self.attr = 2
.... c = C()
print c.attr 2 print c.__class__.att r 1


HTH
Sean
Jul 18 '05 #3
On Wed, Aug 27, 2003 at 04:43:03PM -0700, Brian Munroe wrote:
I was wondering if someone could explain if there is any difference
between initalizing your object attributes up in the __init__
constructor or setting them up as (I am guessing at the name here)
object level variables (like z)


Generally, if something is more or less constant, I make it a class
variable. If its value depends on the arguments passed to __init__, or
if it is something like a network connection, file operation, etc, then
it goes in __init__.

class Foo:
specialSequence = "blahblah"

def __init__(self, filename):
self.fp = file(filename, "r")
if self.fp.read(8) == self.specialSeq uence:
# .. do something ..

specialSequence has no reason to be in the constructor, but fp does. I
suppose that's a good guideline - if you can't think of a reason for it
to be in __init__, then don't put it there.

--
m a c k s t a n n mack @ incise.org http://incise.org
The four building blocks of the universe are fire, water, gravel and vinyl.
-- Dave Barry

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1999
by: svilen | last post by:
hi. this was named but it is misleading. i want to have the order of setting items in intrinsic dicts (keyword args, or class attributes, etc). which is, a prdered dict trhat matches the source-text sequences.
34
4772
by: SeeBelow | last post by:
I see the value of a class when two or more instances will be created, but Python programmers regularly use a class when there will only be one instance. What is the benefit of this? It has a disadvantage of a whole lot of "self." being required everywhere, making the code less readable. Also, since a strength of Python is rapid application development, it slows one down to have to put in all those self.'s. The code seems much cleaner...
4
8035
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned in "Learning Python" by Mark Lutz and David Ascher. It seems like they are a relatively new feature... It seems to me that any truly OO programming language should support these so I'm sure that Python is no exception, but how can these be...
3
1589
by: kman3048 | last post by:
Hello, as a relative newcomer to Python API programming I've got a problem: To extend Python: - there is an API C call to create a module - there is also a API C call to create a method - there is an API C call to create a Class instance Now, I need to create a Class and fill it with Methods and Variables.
2
4978
by: Ewald R. de Wit | last post by:
I'm running into a something unexpected for a new-style class that has both a class attribute and __slots__ defined. If the name of the class attribute also exists in __slots__, Python throws an AttributeError. Is this by design (if so, why)? class A( object ): __slots__ = ( 'value', ) value = 1 def __init__( self, value = None ):
32
5830
by: Matias Jansson | last post by:
I come from a background of Java and C# where it is common practise to have one class per file in the file/project structure. As I have understood it, it is more common practice to have many classes in a Python module/file. What is the motivation behind it, would it be a bad idea to have a guideline in your project that promotes a one class per file structure (assuming most of the programmers a background similar to mine)?
4
3860
by: chandu | last post by:
Hello, declaring class level variables is good approach or not in c#. in C++ we used prefer diclaring class level variables more than local variables. i had a discussion with somebody that in C# it is disadvantage to diclare class level variables
1
1680
by: neoone | last post by:
Hi, I reported a bug to the bugtracker (issue 1443), but it was rejected with the comment: "Go ask on c.l.py why this is not a bug" After decrypting c.l.py to the name of this group, I'll do as I was told so nicely, because I really think it is a misconcept, and cost me two days because I couldn't believe it. So here's the problem:
11
6260
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as the app is concerned). The problem is, If someone makes a typo, they may get an unexpected error due accidentally calling the original attribute instead of the wrapped version. Does anyone have a simple solution for this?
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10165
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10002
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9044
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2921
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.